What values for checked and selected are false?
In HTML, Boolean attributes such as checked
and selected
are considered true by their mere presence. To make them false, simply omit the attribute altogether.
Unchecked checkbox:
Unselected option:
The principle is clear: no attribute depicts false, while the attribute's presence implies true. Don't bother about "false" or "0" values.
Empty or invalid values? Still checked!
Even if an empty or invalid value is provided to the checked
attribute, the checkbox will be checked. Why? Because HTML sees the checked
attribute's existence, not its value.
When pairing attributes according to XHTML, remember to use checked=""
.
Cross-browser fun facts
Using browser tools like Firebug or IE8's Developer Tools might depict the checked
state with a twist, but the underlying behavior remains same—each checkbox marked with checked
will be checked. Trust me, browsers know their job!
HTML5's true-false wisdom
The HTML5 specification, like a wise old wizard, dictates that the existence of a boolean attribute on an element is equivalent to true. So, checked
and selected
merely need to be there to mean true, their absence means false. Isn't it just beautifully simple?
Crash course in Boolean attributes
Checkbox etiquettes
A checkbox in all modern browsers (including such legends as Firefox 3.6, Chrome 10, and Internet Explorer 8) will be checked as long as it's going along with the checked
attribute:
Select dropdown know-hows
An option inside a select
element feels selected if it gets the selected
attribute. It doesn't care about its value:
HTML5's validity mantra
To be considered valid in HTML5, an attribute must either be an empty string or an ASCII case-insensitive match for the name. But HTML is kind; it treats checkboxes as checked or options as selected even if they have an invalid value.
Pro tips for pro developers
Being aware of these behaviors is the key to writing predictable code. So, here are some quick tips:
- Omit the
checked
orselected
attribute for unchecked checkboxes or unselected options. - Trust the consistency across browsers. Don't rely on "false" values—explicitly remove the attribute.
- Be cautious with DOM manipulation—tweaking an attribute's value might not alter its state.
Was this article helpful?