As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. Any ideas as to what is going on here?
$('td').click(function (e) {
// Toggle checkbox
$('input:checkbox', this).prop('checked', function (i, value) {
return !value;
});
});
Thanks!
/
As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. Any ideas as to what is going on here?
$('td').click(function (e) {
// Toggle checkbox
$('input:checkbox', this).prop('checked', function (i, value) {
return !value;
});
});
Thanks!
http://jsfiddle/Littlebob/56CnR/
Share Improve this question edited May 13, 2014 at 9:24 Littlebob asked May 13, 2014 at 8:29 LittlebobLittlebob 1534 silver badges15 bronze badges 3- 1 What code do you have already? – haxtbh Commented May 13, 2014 at 8:30
- 4 see jsfiddle/arunpjohny/vmQ6e/1 – Arun P Johny Commented May 13, 2014 at 8:39
- Sorry, added in code and a jsfiddle link – Littlebob Commented May 13, 2014 at 9:24
3 Answers
Reset to default 9It's because the <input>
checkbox is inside the <td>
and you have attached click event to the <td>
to overe this, Check for the target type and if it's not input checkbox, you need to process it.
DEMO
$('td').click(function (event) {
if (!$(event.target).is('input')) {
$('input:checkbox', this).prop('checked', function (i, value) {
return !value;
});
}
});
refer
event.target
jQuery.is()
I don't know the context of your code, but you really shouldn't need any jQuery/JavaScript here. This can be done simply with the addition of the label element:
HTML
<table>
<tr>
<td>
<label><input type="checkbox" name="something" value="0"/></label>
</td>
</tr>
</table>
CSS
td {
background-color: #eee;
}
label {
padding: 20px;
cursor: pointer;
display: block;
}
See the demo
$(document).ready(function () {
$(document).on('click', 'tbody td', function (e) {
e.stopPropagation();
var checked= $(this).find('input[type="checkbox"]');
checked.prop('checked', !checked.is(':checked'));
$(this).toggleClass('selected'); // or anything else for highlighting purpose
});
$(document).on('click', 'input[type="checkbox"]', function (e) {
e.stopPropagation();
$(this).parent().toggleClass('selected'); // or anything else for highlighting purpose
});
});
check this JSFiddle