HTML: Checkbox πŸ—Ή

By Xah Lee. Date: . Last updated: .

Here's how to create HTML checkboxes.

Single Check Box

Result:

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

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

value="…" is optional. If omitted, the default value is "on".

Property checked return true if it is checked, 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();
}

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials