I've looked around the site and can't seem to find an answer for this question. Feel free to direct me to said question, if it does indeed exist.
I'm currently trying to do some tree-based checkbox operations, and I've come accross some behavior that I find strange.
In Google Chrome, I find that checking a checkbox leaves some "residue", if you will, that will not allow me to check or uncheck that checkbox using "attrRemove('checked');"
Interestingly enough, Internet Explorer (9) has the result I am going for. Please see this jsFiddle in both Chrome and IE for a good comparison of the effects.
http://jsfiddle.net/xixionia/9K5ft/
Can anyone explain these difference, and how I might be able to check / uncheck a checkbox in chrome which has been checked "by hand" ?
HTML
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
JavaScript
$(':checkbox').click(function(e) {
if($(this).is(':checked')) {
$(':checkbox').attr('checked', 'checked');
} else {
$(':checkbox').removeAttr('checked');
}
});
Thanks in advance for your help. :)
edit:
I was able to find this work around. If anyone else has any other solutions, please let me know, and I'll mark it as the solution. :)
$(':checkbox').click(function(e) {
var value = this.checked;
$(':checkbox').each(function(){ this.checked = value; });
});
edit:
Turns out, this problem is specific to jQuery 1.6. Previous versions of jQuery do not suffer from this issue. However, I have posted a solution here: Setting "checked" for a checkbox with jQuery?
When working with checkboxes (especially complicated logic bases on checkboxes) I always try to avoid jQuery event handlers on the checkboxes. There is a bug in jQuery that has to do with the order of event triggering when clicking on checkboxes and the browser used: You can find a description of part of the problem here. A quote:
It seems that when you trigger the click event on a checkbox, the default behavior (toggling the checked attribute) takes place after event handlers fire. This is opposite of what happens when the browser naturally handles the checkbox click event - the checked attribute is toggled and then the event handlers are executed. This difference in the order of operations between inherent clicking and jQuery's event triggering can cause a big problem if the event handler depends on the status of checkbox in anyway (which, if you have a click handler on a checkbox to begin with means it probably does).
jQuery calls this a feature because it has been around since the beginning and changing it to the correct behaviour would just kill so many existing applications. I often had problems with checkboxes and "checked" just because the event was fired too late. So I just use the native JS way: input.checked .
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