How to select all checkboxes in javascript

Subscribe to my newsletter and never miss my upcoming articles

Have you ever wondered how a single checkbox is used to select all other checkboxes? well, in this tutorial you will learn how to create that with just few lines of javascript.

let's begin, first let's create our HTML file

<div class="main-container" id="main-container">
 <form id="select-all-form" accept-charset="utf-8">
   <div class="checkbox-container" >
   <label>
   <input type="checkbox" name="demo" value="Ruby" />Ruby
</label>

      <label>   <input type="checkbox" name="demo"  value="Haskell" />Haskell
</label>

      <label>   <input type="checkbox" name="demo" value="swift" />Swift</label>

      <label>   <input type="checkbox" name="demo"  value="Javascript" />Javascript</label>

      <label>  <input type="checkbox" name="demo"  value="python" />
      python</label>

      <label>   <input type="checkbox" name="demo"  value="cpp" />c++</label>

  </div>

  <input type="submit" id="submit-btn" value="submit" />
</form>
<label >
   <input type="checkbox" name="select-all" id="select-all" />Select all
</label>
</div>

that's all the HTML file we need. Now let's some CSS to it,

*{
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
  body {
   width:100%;
   min-height: 100vh;
   font-size: 16px;
  }
   .main-container {
    width:20em;
    min-height:25em;
    max-width: 100%;
    margin:0 auto;
    padding:40px 20px 30px;

    border:0.12em solid #888;
   }
   .main-container .checkbox-container{
    display: flex;
    flex-direction: column;
   }
   .checkbox-container label {
    margin:0.5em 0;
    font-size: 1.2em;
    text-transform: capitalize;
   }
   .checkbox-container label input[type=checkbox]{
    padding:0 0.5em;
    margin:0 0.5em;
   }
   input[type=submit]{
    border:0;
    outline: 0;
    background:#78f;
    padding:0.6em 0.8em;
    margin:0.5em 0;
    border-radius:0.4em;
    color:#fff;
    font-size: 1.1em;
   }
   #select-all{
    margin:0.6em ;
   }

looks good, now let's add the main function, which is the javascript part.

let mainCon=document.querySelector('.main-container');
let selectAllForm=mainCon.querySelector('#select-all-form');
 let checkboxes=selectAllForm.querySelectorAll('input[type="checkbox"]');
 const selectAllBtn=mainCon.querySelector('#select-all');
 selectAllBtn.addEventListener('click',(e)=>{
  let selectAll=e.target;
  if(selectAll.checked){
   for(let checkbox of checkboxes) {
    checkbox.checked=true
   }

  }
     else{
       for(let checkbox of checkboxes) {
    checkbox.checked=false
   }
   }

 });

that's all, you have successfully been able to create a select all checkboxes using a single checkbox. here is the final result on codepen.

No Comments Yet