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.
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]")).$('tr :checkbox').live('click', function () {
$(this).closest('tr').toggleClass('selected_row_style');
});
$("checkbox").live("click", function()
{
if (this.checked)
{
$(this).attr('background-color','#FFFFFF');
}
else
{
$(this).attr('background-color','#000000');
}
}
$(this) instead of this ?this.checked) is correct. Also, @Alan, what happens when you uncheck?