Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a checkbox's "checked" attribute return the opposite of it's actual value on click event?

I've got the following HTML

<li><input type="checkbox" /><label>This is the label!</label></li>

I bound a click event to the li, and let the click event bubble up to the li before doing anything else.

$('li').each(function(i){
  var item = $(this);
  var checkbox = $("input[type='checkbox']", item);

  item.bind('click', function(e){
    var isChecked = checkbox.is(':checked');
    console.log(isChecked);
    e.stopPropagation();
  });
});

Starting with an unchecked checkbox, when the click event fires, isChecked returns true when I click on the checkbox, but returns false when I click on the label or li. Does anyone know why?

[EDIT:] To demonstrate the issue, have a look at this http://jsfiddle.net/nYbf6/2/.

  1. Click on the checkbox in the first li.
  2. Click inside the second li, but not on a label or checkbox.

Notice that you can never toggle the checkbox by clicking on the checkbox because the 'checked' attribute always returns what it is not when clicking on the checkbox.

[EDIT:] Found the answer here today: http://www.bennadel.com/blog/1525-jQuery-s-Event-Triggering-Order-Of-Default-Behavior-And-triggerHandler-.htm. I'm not fond of the solution, but it's better than no solution.

like image 389
Kappers Avatar asked Dec 02 '25 13:12

Kappers


1 Answers

the click event of a checkbox fires before the value is changed. This way, if you return false when you override the click event, it stops the checkbox from changing it's value. You should change the event to fire onclick of the checkbox, not the li that contains it.

like image 187
Mike Sherov Avatar answered Dec 05 '25 02:12

Mike Sherov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!