What's the proper value for a checked attribute of an HTML checkbox?
The correct way to designate a checkbox as checked in HTML is by adding the standalone attribute checked
:
The presence of checked
implies the checkbox is selected. The checked
attribute is a boolean attribute. Its existence on the element is enough for it to take effect. Consequently, writing checked="checked"
is also valid but unnecessary.
To ensure compatibility with XHTML, consider using checked="checked"
. However, the briefer checked
syntax is recommended for HTML according to HTML5 standards.
The joy of booleans
In the world of HTML, there are boolean attributes, which are evaluated based on their presence (true) or absence (false) —no middle ground here. The checked
attribute is one of these booleans: it's either there (the checkbox is checked) or it's not (checkbox is unchecked). A simple mantra to remember:
- A checkbox with
<input type="checkbox" checked>
is marked. It's like a "high five"—completed and successful 🖐️. - On the other hand,
<input type="checkbox">
represents an open hand—waiting for the completion 🤚.
Dive into the attribute pool
Attribute values in boolean attributes
Assigning a value to a boolean attribute like checked
is less about strict requirements and more about style preference and XHTML compliance. In stricter doctypes like XHTML, checked="checked"
or checked="true"
ensure well-structured markup. But for modern HTML, checked
is sufficient and cleaner.
Javascript & checkbox states
When it's time to chair a discussion with JavaScript, you can set the checked
state via the property:
Alternatively, use setAttribute
to add **checked** or
removeAttribute` to remove it.
Missteps with "checked"
Stay clear from using values like "false"
, "0"
, or "unchecked"
to indicate an unchecked state. They're not valid and can cause unpredictability across browsers. To indicate unchecked states, simply neglect the checked
attribute.
Was this article helpful?