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 falseworks is by combiningevent.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…) andevent.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:JS Fiddle demo.
Incidentally, it’s worth pointing out that
live()is deprecated in jQuery 1.7 and above (replaced by theon()method), and in versions before jQuery 1.7 the docs (forlive()) recommend usingdelegate()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).