What is the difference between the below two usages?
document.getElementById('myRadio').checked = "checked";
and
document.getElementById('myRadio').checked = true;
For me, both are behaving the same way. But, I am just curious to know why there exist two methods to do the same.
Which one will be the ideal usage? I need to support IE7 and higher versions.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.
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');
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.
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