Reputation: 4873
I have multiple tables on a page. For each table, I want to be able to toggle a class on the click of the tr.
So far this is what I have for js:
$(document).ajaxSuccess(function () {
$("table tr").click(function () {
if ($(this).closest("table tr").hasClass("selected_row"))
{ $(this).closest("table tr").removeClass("selected_row"); }
else { $(this).closest("table tr").addClass("selected_row"); }
});
});
Now the issue I'm having is that when I click on a second tr within this table, the previous row keeps the class that was added to it. How can I make it so that on any table, only 1 tablerow may have this class at a time.
Also not, there are sometime multiple tables on the page, so the solution needs to be relevant only to the table being clicked, not all tables on page.
Thanks, Mark
Upvotes: 0
Views: 1592
Reputation: 32581
Closest gets the parent of your selector, this is already table tr, try this :
if ($(this).hasClass("selected_row")) {
$(this).removeClass("selected_row");
} else {
$(this).addClass("selected_row");
$(this).siblings().removeClass('selected_row');
}
Upvotes: 4
Reputation: 207501
There is no need to add an onclick handler to every table row. Use event bubbling to your advantage. Use siblings to get the one that has the class if it exists.
$("table tbody").on("click", "tr", function() {
var row = $(this);
row.toggleClass("selected_row");
row.siblings("selected_row").removeClass("selected_row");
});
Upvotes: 1