mercredi 6 mai 2020

I need to validate validate a checkbox in JS to ensure at least two boxes are ticked

I have the following code below that I can't seem to be able to trigger the notification pop-up. I am not sure if it is I should be calling it by Id or by Name, but neither of the options work. Does anyone have any ideas on what I need to include to get it to return a pop up that ensures the user only selects two of the boxes, and that if they only check one, they are prompted to check for another?

  var valid = false;
    if(document.getElementByName("Q2a").checked) {
      valid = true;
    }
    else if(document.getElementByName("Q2b").checked) {
      valid = true;
    }
    else if(document.getElementByName("Q2c").checked) {
      valid = true;
    }
    else if(document.getElementByName("Q2d").checked) {
      valid = true;
    }
    
    if(valid) {
      alert("Validation successful");
    }
    else {
      alert("Please select at least two checkboxes");
      return false;
    }
  }
    <li>
                <p id="Q2">Which TWO of the following statements are TRUE?</p>
                <div>
                        <input type="checkbox" name="Q2a" id="Q2a" /> <label for="Q2a">a) Another word for fingerspelling is <b>dactylogy</b></label><br />
                        <input type="checkbox" name="Q2b" id="Q2b" /> <label for="Q2b">b) The first known school for the deaf was founded in 1670</label><br />
                        <input type="checkbox" name="Q2c" id="Q2c" /> <label for="Q2c">c) Sign languages are also used by hearing individuals</label><br />
                        <input type="checkbox" name="Q2d" id="Q2d" /> <label for="Q2d">d) There are only 142 sign languages that exist worldwide</label>
                </div>
        </li>



Aucun commentaire:

Enregistrer un commentaire