Reputation: 3661
Using this function. But it adds row_selected class to all rows. How can I add it, only to parent row?
$('.checkbox').click( function() {
if ( $("#list tr").hasClass('row_selected') )
$("#list tr").removeClass('row_selected');
else
$("#list tr").addClass('row_selected');
} );
Upvotes: 0
Views: 1248
Reputation: 150010
You can use the .closest() method
to find the nearest parent (or grandparent/ancestor) element matching a particular selector. So try this:
$('.checkbox').click( function() {
$(this).closest("tr").toggleClass("row_selected");
});
Note that the .toggleClass() method
takes care of your if/else for you, but if you really want to code it manually:
$('.checkbox').click( function() {
// store the reference to the containing tr in a variable instead of
// reselecting it
var $tr = $(this).closest("tr");
if ($tr.hasClass('row_selected') )
$tr.removeClass('row_selected');
else
$tr.addClass('row_selected');
});
Note that either way, in a jQuery event handler this
is the element the event was triggered on, so you can manipulate it or find its parents/siblings/whatever by getting a jQuery object with $(this)
.
Upvotes: 4