HTML: Checkbox πΉ
Here's 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>
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); 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(); }