Explain Codes LogoExplain Codes Logo

What's the proper value for a checked attribute of an HTML checkbox?

html
boolean-attributes
checked-attribute
html-checkbox
Anton ShumikhinbyAnton Shumikhin·Jan 21, 2025
TLDR

The correct way to designate a checkbox as checked in HTML is by adding the standalone attribute checked:

<input type="checkbox" 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:

// Epiphany moment in JavaScript document.getElementById('checkbox').checked = true; // "let there be checks!" and there were checks.

Alternatively, use setAttribute to add **checked** or removeAttribute` to remove it.

// Alternatively, the 'God' mode a.k.a direct HTML attribute manipulation document.getElementById('checkbox').setAttribute('checked', ''); // "let there be checks!" // or document.getElementById('checkbox').removeAttribute('checked'); // "And the checks were gone!"

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.