My checkbox in the table is not immediately set

I have a table with checkboxes. When the checkbox is checked, I catch the event using jquery, but this checkbox is not checked immediately.

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?

Thanks.

UPDATE ------------------

Sorry, I updated my jsfiddle here: http://jsfiddle.net/K4uDa/1/

I added "return false" because I do not want another event to fire when the checkbox is checked or unchecked.

+4
source share
4 answers

The return false method is to combine event.preventDefault() (which, as the name implies, prevents the default action, equal to the standard, for example, removing / checking a flag, by link or submitting a form ...) and event.stopPropagation() ( this is what stops the event from spreading to / being "heard" by its ancestor elements). IE does this a little differently, but effectively you want to keep the default action (un / check), discarding the distribution. Therefore, bearing in mind, I would suggest:

 $('input:checkbox').click(function(e){ e.stopPropagation(); alert(this.checked); }); 

JS Fiddle demo .

By the way, it is worth noting that live() deprecated in jQuery 1.7 and later (replaced by the on() method), and in versions prior to jQuery 1.7, documents (for live() ) recommend using delegate() instead,

But given that you are attaching events directly to the elements themselves, which assumes they are not dynamically added, you can simply simply use the click() method.

Literature:

+4
source

Instead of return false you should use event.stopPropagation(); . return false , in addition to stopping the distribution (which is what you need), also prevents the default action caused by the event, so your checkbox will not be checked.

Also, live() deprecated, so use .on() (or delegate() for <1.7).

 $("table tr td").on("click", "input:checkbox", function(e) { alert('checked/unchecked'); e.stopPropagation(); }); 

jsFiddle Demo

+3
source

EDIT - you need to stop the event from bubbling using event.stopPropagation() instead of return false

http://jsfiddle.net/K4uDa/16/

+1
source

This is due to return false , which stops checking the checkbox.

0
source

All Articles