Toggle Select All Checkbox JavaScript

Toggle Select All Checkbox JavaScript
Code Snippet:Check All - Javascript
Author: Luis
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 12,206
License: MIT
Edit Code online: View on CodePen
Read More

A very Simple pure JavaScript function to check all check fields. It loop through all input with type checkbox and apply checked attribute if select all checkbox checked. This JavaScript code snippet helps you to create toggle select all checkbox functionality.

How to Create Toggle Select all Checkbox in JavaScript

1. First of all, create the HTML structure as follows:

 <h3>Check All  - Javascript</h3>
<div class="container">
<input type="checkbox" id="cc" onclick="javascript:checkAll(this)"/>
<label for="cc">Check All</label>
<br /><br />
<input type="checkbox" id="c1" />
<label for="c1">Checkbox 1</label>
<br />
<input type="checkbox" id="c2" />
<label for="c1">Checkbox 2</label>
<br />
<input type="checkbox" id="c3" />
<label for="c1">Checkbox 3</label>
<br />
<input type="checkbox" id="c4" />
<label for="c1">Checkbox 4</label>
<br />
<input type="checkbox" id="c5" />
<label for="c1">Checkbox 5</label>
<br />  
 </div>

2. After that, add the following CSS styles to your project:

body {
  font-family: segoe ui;
}
.container{
    user-select: none;
}

3. Finally, add the following JavaScript code and done.

function checkAll(o) {
  var boxes = document.getElementsByTagName("input");
  for (var x = 0; x < boxes.length; x++) {
    var obj = boxes[x];
    if (obj.type == "checkbox") {
      if (obj.name != "check")
        obj.checked = o.checked;
    }
  }
}

That’s all! hopefully, you have successfully integrated this toggle select all checkbox code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X