Search code examples
javascripthtmlcheckboxaddeventlistenerselectors-api

How to display an alert when only three of nine checkboxes are checked?


I have implemented the following code into my website to produce an alert when three checkboxes named "correct" are checked.

<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>

const correctInputs = [...document.querySelectorAll('input[name="correct"]')];

const alertIfThree = () => {
  const checkedCorrectInputs = correctInputs.filter(input => input.checked);
  if (checkedCorrectInputs.length > 2) {
    alert('Alert');
  }
};

correctInputs.forEach(input => input.addEventListener('click', alertIfThree));

However, I also have 6 checkboxes named "incorrect" and when any of these checkboxes are checked I don't want the alert to be produced, even if the three "correct" checkboxes are checked.

<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>

How can I change my code to implement this? Thanks in advance!


Solution

  • You can keep the same logic

    const correctInputs = [...document.querySelectorAll('input[name="correct"]')];
    const incorrectInputs = [...document.querySelectorAll('input[name="incorrect"]')];
    
    const alertIfThree = () => {
        const checkedCorrectInputs = correctInputs.filter(input => input.checked);
        const checkedIncorrectInputs = incorrectInputs.filter(input => input.checked);
    
        if (incorrectInputs.length === 0 && checkedCorrectInputs.length > 2) {
            alert('Alert');
        }
    };