HTML: Checkbox β˜‘

By Xah Lee. Date: . Last updated: .

Here is how to create HTML checkboxes.

Single Check Box

Result:

<input id="checkbox1" type="checkbox" name="married" value="married" checked>
<label for="checkbox1">Married</label>

<p>Result: <span id="showbox1"></span></p>

In JavaScript, the property checked is true if it is on, else false.

{
    const checkbox1 = document.getElementById("checkbox1");
    const showbox1 = document.getElementById("showbox1");
    const f_update = (() => {
        showbox1.textContent = checkbox1.checked.toString();
    });
    checkbox1.addEventListener("input", f_update, false);
    f_update();
}

Check Boxes Group

Multiple checkboxes can be done as a group.

Result:

<label><input type="checkbox" name="checkbox68587" value="aa" checked>aa</label>
<label><input type="checkbox" name="checkbox68587" value="bb" checked>bb</label>
<label><input type="checkbox" name="checkbox68587" value="cc">cc</label>
<label><input type="checkbox" name="checkbox68587" value="dd">dd</label>

<p>Result:<br /> <span id="showbox2"></span></p>
{
const showbox2 = document.getElementById ('showbox2');
const checkbox68587 = document.querySelectorAll ( 'input[name="checkbox68587"]');

const f_update = (() => {
let result = [];
const checkedList = document.querySelectorAll ( 'input[name="checkbox68587"]:checked' );

Array.from ( checkedList ) .forEach ((x => { result.push(x.value); }) );
showbox2 .textContent = result.join (', ');
});

// add event
Array.from ( checkbox68587 ) .forEach ((x => { x.addEventListener ('input', f_update, false); }));

f_update();
}
BUY Ξ£JS JavaScript in Depth