Should setting `checkbox.checked = false` not clear the HTML attribute too?

Kev picture Kev · Dec 4, 2009 · Viewed 31.7k times · Source

Here's my HTML:

<input id="test" type="checkbox" checked="">

Here's a Firebug excerpt:

>>> test
<input id="test" type="checkbox" checked="">

>>> test.checked = false
false

>>> test
<input id="test" type="checkbox" checked="">

Um...am I missing something, or should that last line not read the following?

<input id="test" type="checkbox">

UI-wise, the checkbox does indeed uncheck when I execute the checked = false line.

Anyway, if there's some legitimate explanation for this, then what's the proper way to uncheck a checkbox from JavaScript, if not checked = false?

Answer

bobince picture bobince · Dec 4, 2009

The value attribute of input type="text" and the checked or selected attributes of input type="checkbox", radio and option correspond to the initial value of the form field, not the current value the user or script has set. Consequently changing the checked property does not alter the attribute value, and setting the checked attribute does not alter the real visible value that's going to be submitted with the form.

The checked="checked" attribute corresponds to the defaultChecked DOM property, not the checked property. Similarly, the value="..." attribute corresponds to defaultValue.

(Note there are IE gotchas here due to IE not knowing the difference between a property and an attribute.)