Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in parameter from html element with jQuery

I'm working with jQuery for the first time and need some help. I have html that looks like the following:

<div id='comment-8' class='comment'>
    <p>Blah blah</p>
    <div class='tools'></div>
</div>

<div id='comment-9' class='comment'>
    <p>Blah blah something else</p>
    <div class='tools'></div>
</div>

I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.

What I have thus far is:

<script type='text/javascript'>

    $(function() {
        var actionSpan = $('<span>[Do Something]</span>');
        actionSpan.bind('click', doSomething);

        $('.tools').append(actionSpan);
     });

     function doSomething(commentId) { alert(commentId); }

</script>

I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.

Thanks, Brian

like image 682
Brian Vallelunga Avatar asked Dec 06 '25 04:12

Brian Vallelunga


2 Answers

Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a target property that references the element it was called for, and the this variable is a reference to the element the event handler was attached to. So you could do the following:

function doSomething(event)
{
    var id = $(event.target).parents(".tools").attr("id");
    id = substring(id.indexOf("-")+1);
    alert(id);
}

...or:

function doSomething(event)
{
    var id = $(this).parents(".tools").attr("id");
    id = substring(id.indexOf("-")+1);
    alert(id);
}
like image 137
Jim Avatar answered Dec 08 '25 18:12

Jim


To get from the span up to the surrounding divs, you can use <tt>parent()</tt> (if you know the exact relationship), like this: <tt>$(this).parent().attr('id')</tt>; or if the structure might be more deeply nested, you can use parents() to search up the DOM tree, like this: <tt>$(this).parents('div:eq(0)').attr('id')</tt>.

To keep my answer simple, I left off matching the class <tt>"comment"</tt> but of course you could do that if it helps narrow down the div you are searching for.

like image 25
andy Avatar answered Dec 08 '25 18:12

andy