How do I add event listeners to check the number of checkboxes selected on a page and display an alert?


So I have a web page that contains a list of 20 checkboxes. If the user ticks any 5 of them, I want to give an alert saying that they have made the maximum number of choices.

let checked=document.getElementsByClassName("chkbox"); //classname added to each checkbox in html

checked.addEventListener('change', () => {

  let counter=0;
    for(let i=0;i<checked.length;i++){ //to update counter each time a checkbox gets changed
        if(checked[i].checked){
        counter++;
        }
    }
    if(counter==5){
            alert("You have made maximum choices. Proceed to next form")
        }

})

---------------Answer---------------

You can do so by checking number of ticked boxes whenever a user clicks on the box.

You can read the comments in the code to better understand it

// Defind how many check boxes a user can check
// You requested 5 but to make it less html code, I put 2 in the variable below
var checkboxLimit = 2;

// Get every check box by using querySelectorAll
document.querySelectorAll("input[type=checkbox]").forEach(
// For each check box add on click event listener
  input => input.addEventListener('click', function(event) {
  // get number of check boxes by passing :check attribute to the query selector
    var numberTickedBoxes = 
      document.querySelectorAll("input[type=checkbox]:checked").length;
    
    // check if the number of ticked boxes are more than allowed limit
    if(checkboxLimit < numberTickedBoxes){
      alert("You are allowed to check " + checkboxLimit + " boxes")
    }
  })
);
<label>1</label>
<input type="checkbox" name="test" value="1" />
<br/>
<label>2</label>
<input type="checkbox" name="test" value="2" />
<br/>
<label>3</label>
<input type="checkbox" name="test" value="3" />
<br/>
---------------Answer---------------

You should look at the "disabled" attribute of checkboxes rather than alerting the user so he won't be able to check any other boxes. You still have to have a check counter in your JS to know when to activate the disabled attribute of your inputs.

---------------Answer---------------

First you fetch the checkboxes. Then you can iterate over the HTMLCollection. Inside the loop you check if the property checked is set. If yes increase the counter by one.

const fs = document.getElementsByTagName('fieldset')
var cb = document.querySelectorAll("input[name=favorite_pet]");
const limit = 2;
let counter = 0;


for (let i = 0; i < cb.length; i++) {  
  cb[i].addEventListener('change', function() {
    if (this.checked) {
      console.log("Checkbox is checked..");
      counter++;
    } else {
      counter--;
      console.log("Checkbox is not checked..");
    }
    if (counter >= 2) {
      alert('warning')
    }
    console.log(counter)
  });    
}
<fieldset>      
    <legend>What is Your Favorite Pet?</legend>      
    <input type="checkbox" name="favorite_pet" value="Cats" >Cats<br>      
    <input type="checkbox" name="favorite_pet" value="Dogs">Dogs<br>      
    <input type="checkbox" name="favorite_pet" value="Birds" >Birds<br>      
    <br>      
    <input type="submit" value="Submit now" />      
</fieldset>  

Previous : Only show specific styling if certain theme
Next : How to force HTTPS on all URL's except one directory /images using .htaccess?