Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeAttribute('checked') not working

I encounter a strange problem concerning checkboxes. For various reasons I have to programmaticaly check or uncheck checkbox inputs depending on the context of my application.

But for an unknown reason I unable to uncheck the checkbox. Searching on the internet teach me to remove the "checked" attribute in order to uncheck the box, as "checked" is a binary attribute : Check/Uncheck checkbox with javascript? and Remove attribute "checked" of checkbox

None of these subjects (and many other that I read) are useful in my case : I don't want to use jQuery, so the logical way to do the same is to use removeAttribute function, just like that :

document.getElementById('box').removeAttribute('checked');

It seems to be executed but no effect is visible.

My code is a bit to complex and huge to post it here, so I made a more relevant jsFiddle to show you the problem : https://jsfiddle.net/54fd795w/

By using the buttons, whatever the state of the box is, you can see that the button used to check the box is working, whereas the button to uncheck is not.

Any ideas for make it work or find a workaround ? Thanks.

like image 227
2 revs Avatar asked Jan 06 '23 20:01

2 revs


1 Answers

The checked attribute describes the default state of the field. Removing it will have no effect if the field has been interacted with (or if its checked property has already been modified).

Set the checked property instead. It represents the current state.

document.getElementById('box').checked = false;

Note that in your third party hosted example, in the "Click me to check" code:

document.getElementById('box').checked = "checked";

… you are modifying the property and the string "checked" is being converted to the boolean true. The checked property only accepts a boolean. This is overriding the default state (unchecked because there is no checked attribute).

You never even have a checked attribute to remove.

like image 81
Quentin Avatar answered Jan 17 '23 15:01

Quentin