Implementing a "Select All" Checkbox in HTML
In web development, it is common to encounter situations where users need to select multiple items from a list. A versatile solution to simplify this process is to implement a "Select All" checkbox. When ticked, this checkbox should automatically select all other checkboxes on the page.
JavaScript Solution
To achieve this functionality, you can employ JavaScript. Here's a code snippet that demonstrates the implementation:
function toggle(source) { checkboxes = document.getElementsByName('foo'); for (var i = 0, n = checkboxes.length; i < n; i++) { checkboxes[i].checked = source.checked; } }
HTML Integration
Incorporate the JavaScript function into your HTML code as follows:
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br /> <input type="checkbox" name="foo" value="bar1" /> Bar 1<br /> <input type="checkbox" name="foo" value="bar2" /> Bar 2<br /> <input type="checkbox" name="foo" value="bar3" /> Bar 3<br /> <input type="checkbox" name="foo" value="bar4" /> Bar 4<br />
Functional Behavior
When the "Toggle All" checkbox is checked, all other checkboxes will be selected. Unchecking it will deselect all other checkboxes. This allows users to quickly select or deselect multiple items with just a single click.
The above is the detailed content of How to Implement a 'Select All' Checkbox in HTML?. For more information, please follow other related articles on the PHP Chinese website!