Reputation: 8892
I have a dynamically generated table of n rows with a checkbox in each row. How can I make that table row have a different background-color when its checkbox is checked?
I have no problem using jQuery if need be.
Upvotes: 2
Views: 5182
Reputation: 652
$("checkbox").live("click", function()
{
if (this.checked)
{
$(this).attr('background-color','#FFFFFF');
}
else
{
$(this).attr('background-color','#000000');
}
}
Upvotes: 0
Reputation: 1075765
If you're using jQuery, dead simple:
$("tr :checkbox").live("click", function() {
$(this).closest("tr").css("background-color", this.checked ? "#eee" : "");
});
Basically what that does is identify checkboxes that are contained in a row, watch for clicks on them, and then use their state within the event handler to set the background-color
CSS style on the row containing the checkbox.
Things to consider augmenting/modifying:
live
in case the table is dynamic on the client (e.g., if you add or remove rows), although you may prefer to use delegate
rooted in the table instead. If the table will be completely static, you might just use click
.$("tr :checkbox.foo")
where "foo" is the class) or checkbox name ($("tr :checkbox[name=foo]")
).Upvotes: 7
Reputation: 9474
$('tr :checkbox').live('click', function () {
$(this).closest('tr').toggleClass('selected_row_style');
});
Upvotes: 2