I have a table with checkboxes. When a checkbox is checked I catch the event with jQuery but this checkbox is immediately unchecked.
The jsfiddle: http://jsfiddle.net/K4uDa
<table>
<tr>
<td><input type='checkbox' /></td><td>AA</td>
</tr>
<tr>
<td><input type='checkbox' /></td><td>BB</td>
</tr>
<tr>
<td><input type='checkbox' /></td><td>CC</td>
</tr>
</table>
$(function() {
$("table tr").live("click", function() {
alert('row clicked');
});
$("table tr td input:checkbox").live("click", function() {
alert('checked/unchecked');
return false;
});
})
Where is the problem?
Sorry, I updated my jsfiddle here: http://jsfiddle.net/K4uDa/1/
I added a 'return false' because I don't want the other event to fire when a checkbox is checked/unchecked.
The way return false
works is by combining event.preventDefault()
(which as the name implies prevents the default action of the even, such as un/checking the checkbox, following a link or submitting a form...) and event.stopPropagation()
(which is what stops the event from propagating to/being 'heard by' its ancestor elements). IE does it a little differently, but effectively you want to retain the default action (the un/checking) while discarding the propagation. So, with that in mind I'd suggest:
$('input:checkbox').click(function(e){
e.stopPropagation();
alert(this.checked);
});
JS Fiddle demo.
Incidentally, it's worth pointing out that live()
is deprecated in jQuery 1.7 and above (replaced by the on()
method), and in versions before jQuery 1.7 the docs (for live()
) recommend using delegate()
instead.
But given that you're binding events directly to the elements themselves, which suggests they're not dynamically added, you may as well simply use the click()
method directly.
References:
click()
.delegate()
.event.preventDefault()
.event.stopPropagation()
.live()
.on()
.window.event.cancelBubble
(at MSDN).Instead of return false
, you should use event.stopPropagation();
. return false
, besides stopping propagation (which is what you want), also prevents the default action triggered by the event, so your checkbox will not be checked.
Also, live()
is deprecated, so please use .on()
(or delegate()
for <1.7).
$("table tr td").on("click", "input:checkbox", function(e) {
alert('checked/unchecked');
e.stopPropagation();
});
jsFiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With