HTML: the checked attribute
The checked attribute makes a checkbox or radio button selected in its initial state.
What you will learn
- How to make a checkbox or radio button initially selected
- How the initial state differs from the current state after user interaction
- How JavaScript
checked,defaultChecked, and form submission relate
Basic examples
<label>
<input type="checkbox" name="updates" checked>
Send me updates
</label>
<label>
<input type="radio" name="plan" value="monthly" checked>
Monthly plan
</label>
The boolean attribute means “initially selected.” Its value does not need to be true; writing the attribute is enough. Pair controls with visible labels so people know what they are selecting.
Initial state and current state
const checkbox = document.querySelector('input');
console.log(checkbox.defaultChecked); // initial HTML state
console.log(checkbox.checked); // current state
checkbox.checked = false; // change current state
defaultChecked reflects the initial markup. The checked property reflects the current state and changes when the user or a script toggles the control.
Form submission
A checked checkbox contributes its name and value when the form is submitted. An unchecked checkbox contributes nothing. For radio buttons, the selected member of the same named group contributes its value.
Common mistakes
- Expecting the
checkedattribute to keep the control selected after the user changes it. - Reading an attribute with
getAttributewhen the current property is needed. - Using several checked radio buttons with the same name and expecting all of them to remain selected.
- Forgetting the
nameattribute, so the control contributes no form data.