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
            alert("You have made maximum choices. Proceed to next form")



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
// 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 = 
    // check if the number of ticked boxes are more than allowed limit
    if(checkboxLimit < numberTickedBoxes){
      alert("You are allowed to check " + checkboxLimit + " boxes")
<input type="checkbox" name="test" value="1" />
<input type="checkbox" name="test" value="2" />
<input type="checkbox" name="test" value="3" />

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.


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..");
    } else {
      console.log("Checkbox is not checked..");
    if (counter >= 2) {
    <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>      
    <input type="submit" value="Submit now" />      

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