Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My checkbox in a table is immediately unchecked

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.

like image 202
Bronzato Avatar asked Feb 17 '23 16:02

Bronzato


2 Answers

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).
like image 185
David Thomas Avatar answered Feb 20 '23 09:02

David Thomas


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

like image 38
kapa Avatar answered Feb 20 '23 08:02

kapa