2

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.

3 Answers 3

7

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Upvote from me as I nicked your selectors (was using css class and parents instead of closest).
2
$('tr :checkbox').live('click', function () {
    $(this).closest('tr').toggleClass('selected_row_style');
});

1 Comment

And right back atcha, using a class rather than inline style. Better for decoupling.
0
$("checkbox").live("click", function()
{ 
    if (this.checked) 
    {
       $(this).attr('background-color','#FFFFFF');
    }
    else
    {
       $(this).attr('background-color','#000000');
    }
}

3 Comments

Aren't you trying to change the background of the input element instead of the parent cell/row? Also, you probably meant $(this) instead of this ?
@AJweb: The second time, yeah; the first one (this.checked) is correct. Also, @Alan, what happens when you uncheck?
Thanks for pointing me out my mistakes, i was in too much hurry :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.