checked = "checked" vs checked = true
document.getElementById('myRadio').checked
is a boolean value. It should be true
or false
document.getElementById('myRadio').checked = "checked";
casts the string to a boolean, which is true.
document.getElementById('myRadio').checked = true;
just assigns true
without casting.
Use true
as it is marginally more efficient and is more intention revealing to maintainers.
The element has both an attribute and a property named checked
. The property determines the current state.
The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.
If there is no value for the attribute in the markup, the attribute becomes null
, but the property is always either true
or false
, so it becomes false
.
When you set the property, you should use a boolean value:
document.getElementById('myRadio').checked = true;
If you set the attribute, you use a string:
document.getElementById('myRadio').setAttribute('checked', 'checked');
Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.
Note also that whatever value you set the attribute to, the property becomes true
. Even if you use an empty string or null
, setting the attribute means that it's checked. Use removeAttribute
to uncheck the element using the attribute:
document.getElementById('myRadio').removeAttribute('checked');
The original checked
attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.
This, however is not valid for XHTML that followed HTML 4.
The standard proposed to use checked="checked"
as a condition for true - so both ways you posted end up doing the same thing.
It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).
document.getElementById('myRadio')
returns you the DOM element, i'll reference it as elem
in this answer.
elem.checked
accesses the property named checked
of the DOM element. This property is always a boolean.
When writing HTML you use checked="checked"
in XHTML; in HTML you can simply use checked
. When setting the attribute (this is done via .setAttribute('checked', 'checked')
) you need to provide a value since some browsers consider an empty value being non-existent.
However, since you have the DOM element you have no reason to set the attribute since you can simply use the - much more comfortable - boolean property for it. Since non-empty strings are considered true
in a boolean context, setting elem.checked
to 'checked'
or anything else that is not a falsy value (even 'false'
or '0'
) will check the checkbox. There is not reason not to use true
and false
though so you should stick with the proper values.