Reputation: 520
I am trying to allow my users to press on the table row to check a checkbox.
<table>
<tr>
<td onclick="toggleIt(this)">
<input type="checkbox"/> Option 1
</td>
</tr>
<tr>
<td onclick="toggleIt(this)">
<input type="checkbox"/> Option 2
</td>
</tr>
</table>
function toggleIt(myTd) {
$(myTd).find('input').prop('checked', !$(myTd).find('input').prop('checked'));
}
This works great until you press the checkbox itself, then it wont work. My guess is that the checkbox checks itself, then the javascript is run and it reverses it again.
jsFiddle: http://jsfiddle.net/toxu1v2o/1/
EDIT: Sorry for not clarifying, I need to be able to press the whole td
tag, This wont work with labels: http://jsfiddle.net/toxu1v2o/4/
SOLUTION:
Instead of using this
, use event
. Then check if its the checkbox being pressed or not. Something like this:
http://jsfiddle.net/toxu1v2o/17/
Upvotes: 0
Views: 369
Reputation: 337560
You don't need JavaScript for this - just wrap the checkbox
and the text in a <label />
element:
td {
background-color: #F0F0F0;
}
label {
padding: 40px;
display: block;
}
<table>
<tr>
<td>
<label>
<input type="checkbox" />Option 1
</label>
</td>
</tr>
<tr>
<td>
<label>
<input type="checkbox" />Option 2
</label>
</td>
</tr>
</table>
Upvotes: 3
Reputation: 7558
you can try in this way
<table>
<tr>
<td>
<label for="cb1">Op1</label>
<input id="cb1" type="checkbox"/>
</td>
</tr>
<tr>
<td>
<label for="cb2">Op2</label>
<input id="cb2" type="checkbox"/>
</td>
</tr>
</table>
Upvotes: 1
Reputation: 332
Does this work for you? And what version of jquery are you using?
$('td').click(function(){
$('input[type="checkbox"]').attr('checked', 'true');
});
Upvotes: 0