Home > Web Front-end > JS Tutorial > body text

How to Implement a 'Select All' Checkbox in HTML?

Susan Sarandon
Release: 2024-11-11 05:01:02
Original
242 people have browsed it

How to Implement a

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;
  }
}
Copy after login

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 />
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template