F__M
F__M

Reputation: 1598

Select checkbox when clicking on the <tr> in jQuery

I've the following HTML code:

<table class="table table-striped">
    <thead>
        <tr>
            <th></th>
            <th>Color</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="checkbox checkbox-primary">
                    <input type="checkbox" name="elements_ids">
                    <label></label>
                </div>
            </td>
            <td>Blue</td>
        </tr>
        ...
    </tbody>
</table>

How with jQuery I can checked the checkbox if I click on the <tr> but only if this <tr> got a checkbox to check. I do not want this code affects all my table on my page.

I tried:

$(".table tbody tr").has(':checkbox').change(function(e){
    alert('ee');
});

Additionally, how can I revert this if the checkbox is checked ?

Could you please help ?

Upvotes: 0

Views: 3097

Answers (2)

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

Find the checkbox in tr in the click event of it and then set checkbox status using prop() method like following.

$(".table tbody tr").click(function(e) {
    if($(e.target).is(':checkbox')) return; //ignore when click on the checkbox
  
    var $cb = $(this).find(':checkbox');
    $cb.prop('checked', !$cb.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
    <thead>
        <tr>
            <th></th>
            <th>Color</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="checkbox checkbox-primary">
                    <input type="checkbox" name="elements_ids">
                    <label></label>
                </div>
            </td>
            <td>Blue</td>
        </tr>
    </tbody>
</table>

Upvotes: 2

Dipiks
Dipiks

Reputation: 3928

There is a jsfiddle

And the javascript for what you need:

$("tr").on("click", function(e){
    $("input[type='checkbox']", this).each( function() {
        $(this).attr('checked', !$(this).attr('checked'));
    });
});

This way it will invert all the checkboxes on the clicked row.

Upvotes: 0

Related Questions