Reputation: 533
When i click TD the input element inside should be selected and vise-versa,
I wrote the below code using jquery which is working fine but when i click on the checkbox it is not working the way a checkbox works, any ideas how to hadle this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$(".mainTable td").click(function (){
var obj = $(this).children('input[type=checkbox]');
var bool = obj.prop("checked");
if(obj.length > 0){
obj.attr("checked",!bool);
}
});
});
</script>
<table cellpadding=10 border=1 class='mainTable'>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<table>
Upvotes: 2
Views: 96
Reputation: 10399
$(".mainTable td").click(function (event){
if (event.target.nodeName === 'INPUT') {
return;
} else {
var obj = $(this).children('input[type=checkbox]');
var bool = obj.prop("checked");
if(obj.length > 0){
obj.attr("checked",!bool);
}
}
});
Upvotes: 1
Reputation: 144729
That's because events bubble up, you can use stopPropagation
method.
$(document).ready(function (){
$(".mainTable td").click(function (){
$('input[type=checkbox]', this).prop('checked', function(i, checked){
return !checked;
})
}).find('input[type=checkbox]').click(function(e){
e.stopPropagation();
})
});
Upvotes: 3