How to select a row in a table using jquery?

I created a table in my application, I want to select (change the background color) an entire row when I click on the checkmark, just like gmail does. When we click the checkbox in gmail, the whole line turns 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?

+3
source share
3 answers
$(function() {
  $("#chk").click(function() {
    $(this).parents("tr").toggleClass("diffColor");
  });
});

Create a CSS class (called "diffColor" above) and add a background color this way:

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

Do not set CSS attributes directly. Use classes where possible.

+7
source

The answer to Cletus is right, but I think it can be improved a bit:

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

The only real differences are here:

  • <tr>.... , , , .
  • . , - "diffColour" , , , .

, change:

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

, , TableRowSelector.

0

Source: https://habr.com/ru/post/1708054/


All Articles