admin管理员组文章数量:1303335
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
本文标签: javascriptjQuery click on td to toggle checkboxStack Overflow
版权声明:本文标题:javascript - jQuery click on td to toggle checkbox - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741725859a2394617.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论