Demo shows how to toggle or clear checkbox group. On button click, all checkboxes in HTML table will change checked state. Checkbox group can be defined with any container so it’s not necessary to use a table. This is really simple JavaScript function with checkbox toggle and clear options.
Toggle | |
Table 1 | |
Clear |
Toggle | |
Table 2 | |
Clear |
Toggle | |
Table 3 | |
Clear |
JavaScript code uses “trick” to find parent node and this is explained in Find parent node in DOM post. Toggle and clear buttons are located inside TABLE, so it’s only needed to send button reference (keyword “this”) to find parent table. After table reference is found, getElementsByTagName will collect all INPUT elements inside table. For loop will go through each INPUT element and toggle or clear checkbox state. Here is complete JavaScript code used in this example:
/** * Toggle or clear checkboxes in table * @param {HTMLElement} btn Clicked button (button should be inside table) * @param {String} type Toggle or clear (values 'toggle' or 'clear') */ function toggleCheckbox (btn, type) { // eslint-disable-line no-unused-vars // input elements let el; // find parent table from clicked button while (btn && btn.nodeName !== 'TABLE') { btn = btn.parentNode; } // get all input elements inside table el = btn.getElementsByTagName('input'); // loop through all collected input elements for (let i = 0; i < el.length; i++) { // if input element is checkbox if (el[i].type === 'checkbox') { // toggle or clear checkbox state if (el[i].checked || type === 'clear') { el[i].checked = false; } else { el[i].checked = true; } } } }
It is only needed to call toggleCheckbox() function on button click or any other event. Below is HTML for toggle and clear buttons used in each table.
<!-- toggle button --> <input type="button" value="T" onclick="toggleCheckbox(this, 'toggle')" title="Toggle"/> <!-- clear button --> <input type="button" value="C" onclick="toggleCheckbox(this, 'clear')" title="Clear"/>
Source code of this checkbox toggle demo can be download from “download icon” below post. I hope you’ll find this mini tutorial useful for working with checkboxes.
Outstanding work.
Maybe not so outstanding, “useful” is good enough.
;)