Checkbox and radio
Learn to read checkbox and radio states with the checked property.
The checked property
To read whether an <input type="checkbox"> element is selected, you use the checked property. It returns true or false.
const agree = document.querySelector('#agree');
if (agree.checked) {
console.log('Agreed');
}The value property is meaningless for a checkbox; the state is read only through checked. The same property works for radio buttons.
Scanning a radio group
You group several <input type="radio"> elements by giving them the same name value. To get the whole group, you use querySelectorAll.
const radios = document.querySelectorAll('input[name="size"]');
for (const radio of radios) {
if (radio.checked) {
console.log(radio.value);
}
}Only one radio button with the same name can be selected. You look at each one with a loop and find the one that is checked.
Exercise Read checkbox and radio state
The agree variable points to the checkbox named 'agree'. Use its checked property to see if it is selected. Log 'Agreed' if selected, otherwise 'Agreement required'. Then find the selected button in the radio group named 'size' and log its value.
Show example solution
if (agree.checked) {
console.log('Agreed');
} else {
console.log('Agreement required');
}
const radios = document.querySelectorAll('input[name="size"]');
for (const radio of radios) {
if (radio.checked) {
console.log(radio.value);
}
}
Test yourself
-
Select the radio group by name
const radios = document.querySelectorAll('input[____="size"]');Show answer
const radios = document.querySelectorAll('input[name="size"]'); -
Which checks whether a checkbox is selected?
const cb = document.querySelector('#agree'); // A if (cb.value) { console.log('OK'); } // B if (cb.selected) { console.log('OK'); } // C if (cb.checked) { console.log('OK'); } // D if (cb.on) { console.log('OK'); }- A
- B
- C
- D
Show answer
C — Correct! The checked property returns true/false and gives the state.
-
Match properties to their meanings
- checkbox.checked
- Is it selected
- radio.value
- The button's value
- input[name="size"]
- Select by name attribute