HTML: Checkbox πŸ—Ή

By Xah Lee. Date: . Last updated: .

Here's how to create HTML checkboxes.

Single Check Box


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

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

checked is optional. If is there, the checkbox is checked by default.

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);


Check Boxes Group

Multiple checkboxes can be done as a group.


<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); }));


DOM How-To

Web Scripting Overview

HTML Input

Web Scripting Examples

Web Scripting Misc



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