How to highlight table row when clicked on checkbox using jQuery

Here the task is to highlight the table row when clicked anywhere on the table row or simply by clicking on the checkbox. We can do it using jquery.

Here is the code:

<table class="record_table">
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td><a href="#">Hello</a></td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
</table>

CSS code:

.record_table {
    width: 100%;
    border-collapse: collapse;
}
.record_table tr:hover {
    background: #eee;
}
.record_table td {
    border: 1px solid #eee;
}
.highlight_row {
    background: #eee;
}

jQuery code:

$(document).ready(function () {
    $('.record_table tr').click(function (event) {
        if (event.target.type !== 'checkbox') {
            $(':checkbox', this).trigger('click');
        }
    });

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("highlight_row");
        } else {
            $(this).closest('tr').removeClass("highlight_row");
        }
    });
});

You can see the demo with above code on JsFiddle.

Sometimes if you have a hyperlink inside the table then this functionality will override the hyperlink and link will no longer work instead, when the hyperlink is clicked it will select the table row. To overcome this override you can use jquery stop propagation function. Using this function will make hyperlinks clickable again and the remaining functionality is the same.

$('.record_table tr a').click(function(e) {
  e.stopPropagation();
});
Buy me a coffeeBuy me a coffee
Facebooktwittergoogle_plusredditpinterestlinkedinmail