AKor
AKor

Reputation: 8892

Using a checkbox to change table row styling

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

Answers (3)

Alan
Alan

Reputation: 652

$("checkbox").live("click", function()
{ 
    if (this.checked) 
    {
       $(this).attr('background-color','#FFFFFF');
    }
    else
    {
       $(this).attr('background-color','#000000');
    }
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075765

If you're using jQuery, dead simple:

$("tr :checkbox").live("click", function() {
    $(this).closest("tr").css("background-color", this.checked ? "#eee" : "");
});

Live example

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:

  • I used 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.
  • The above hooks all checkboxes inside rows, which is probably more than you want. jQuery supports nearly all of CSS3's selectors and a fair bit more, so you can craft the selector for the checkboxes to make it more narrow. A basic change would be to filter by class ($("tr :checkbox.foo") where "foo" is the class) or checkbox name ($("tr :checkbox[name=foo]")).
  • As Morten suggests below, you might consider adding/removing a class rather than giving the CSS values directly in the code, as that helps decouple your script from your styling.

Upvotes: 7

Morten Mertner
Morten Mertner

Reputation: 9474

$('tr :checkbox').live('click', function () {
    $(this).closest('tr').toggleClass('selected_row_style');
});

Upvotes: 2

Related Questions