Reputation: 1598
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
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