JS DOM: input checkbox ☑
Single Check Box
Result:
Code
<input id="checkbox_B4BWh" type="checkbox" name="married" value="married" checked> <label for="checkbox_B4BWh">Married</label> <p>Result: <span id="output_rp9Z4"></span></p>
value=valis optional. If omitted, the default value is string"on".- The attribute
checkedmeans the state is on.
In JavaScript, the property checked is true if it is on, else false.
{ const checkbox_B4BWh = document.getElementById("checkbox_B4BWh"); const output_rp9Z4 = document.getElementById("output_rp9Z4"); const f_update = () => { output_rp9Z4.textContent = checkbox_B4BWh.checked.toString(); }; checkbox_B4BWh.addEventListener("input", f_update); f_update(); }
Check Boxes Group
Multiple checkboxes can be done as a group.
Result:
Code
<label><input type="checkbox" name="cbox_vdhx" value="aa" checked>aa</label> <label><input type="checkbox" name="cbox_vdhx" value="bb" checked>bb</label> <label><input type="checkbox" name="cbox_vdhx" value="cc">cc</label> <label><input type="checkbox" name="cbox_vdhx" value="dd">dd</label> <p>Result: <span id="output_WvZ99"></span></p>
{ const output_WvZ99 = document.getElementById("output_WvZ99"); const cbox_vdhx = document.querySelectorAll("input[name='cbox_vdhx']"); const f_update = () => { let result = []; const checkedList = document.querySelectorAll("input[name='cbox_vdhx']:checked"); Array.from(checkedList).forEach((x) => { result.push(x.value); }); output_WvZ99.textContent = result.join(", "); }; // add event Array.from(cbox_vdhx).forEach((x) => { x.addEventListener("input", f_update); }); f_update(); }