Friday, May 6, 2011

How to select a row in table using jquery?

I have created a table in my application, I want to select (change background color) whole row on click of a checkbox, same as gmail is doing, When we click checkbox in gmail, the whole row becomes yellow.

<table>
<tbody>
<tr>
<td><input type="checkbox" name="chk" id="chk" /></td>
<td>My Name</td>
<td>Description of the job</td>
</tr>
</tbody>
</table>

Please tell me how to do the same in jquery ?

Thanks

From stackoverflow
  • $(function() {
      $("#chk").click(function() {
        $(this).parents("tr").toggleClass("diffColor");
      });
    });
    

    Create a CSS class (called "diffColor" above) and add the background color that way, something like:

    <style type="text/css">
    tr.diffColor td { background-color: yellow; }
    </style>
    

    Don't set CSS attributes directly. Use classes where possible.

    ichiban : Good explanation +1
  • Cletus's answer is right, but I think can be improved a little:

    $(function() {
        $("#chk").click(function() {
            $(this)
                .parents("tr:first")
                .toggleClass("diffColor", this.checked)
            ;
        });
    });
    

    The only real differences here is:

    1. that it only selects the first parent <tr>. ...you never know where your code might end up, plus, in theory it'll be a couple of ticks faster.
    2. it checks the new value of the checkbox and adds or removes the class as required. Without checking this, some other code might change the "diffColour" class on the row and then your checkbox would be inverted, if you know what i mean.

    Also, you might consider binding that function to the change handler as well:

    $('#chk').bind('click change', function() { // ... etc
    

0 comments:

Post a Comment