Skip to content Skip to sidebar Skip to footer

How To Know Which Jquery Button Was Clicked In List Context

I have a list of stories on a page and each has several jQuery buttons for different actions. When the button is clicked, I need to know what story it is was clicked for. Curren

Solution 1:

You could do it using data attributes as well, possibly removing the need for the parent IDs altogether:

<inputtype="button"class="report-button" data-id="1" value="Report">

Then get it using .attr() on the click event like this:

$(function() {
  $('.report-button').button()
                     .click(function() {                
                       alert($(this).attr('data-id'));
                     });
});

You can give it a try here

Solution 2:

I would do it the way you currently are, but replace .parents with .closest.

Solution 3:

Try something like this.

<inputtype="button"class="report-button" name="story_9" value="Report">

and the javascript:

var id_str = $(this).attr("name");

Solution 4:

I don't think there's really a standard way of doing this. Your technique seems fine.

Now if you are going to submit this id to the server then probably using a form with a hidden field and a submit button is more adapted as you will no longer need to do any parsing or rely on order of DOM elements nesting to extract this id.

Post a Comment for "How To Know Which Jquery Button Was Clicked In List Context"