Home > Net >  How to validate multiple checkboxes in JavaScript?
How to validate multiple checkboxes in JavaScript?

Time:11-27

I have 4 checkboxes, I want to show different alerts for first two when they are selected but not getting the output.Please let me know where it went wrong.

let ReviewCheckBox = checkform.ratings;
if (ReviewCheckBox[0].checked == true) {
  alert("1 Selected");
} else if (ReviewCheckBox[0].checked == true && ReviewCheckBox[1].checked == true) {
  alert("Both Selected");
}
<div>
  <span>CUSTOMER REVIEWS</span><br>
  <form name="checkform" onclick="productFilter()">
    <input type="checkbox" name="ratings" id="rating-checka">
    <label for="rating-checka">4 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkb">
    <label for="rating-checkb">3 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkc">
    <label for="rating-checkc">2 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkd">
    <label for="rating-checkd">1 * & Above</label>
  </form>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

1) You have to validate on every checkbox checked so for this you can create a function productFilter and it will run every time you checkbox

2) You have to check for 0 and 1 index checkbox first than only 0.

function productFilter() {
  let ReviewCheckBox = checkform.ratings;
  if (ReviewCheckBox[0].checked == true && ReviewCheckBox[1].checked == true) {
    alert("Both Selected");
  } else
  if (ReviewCheckBox[0].checked == true) {
    alert("1 Selected");
  }
}
<div>
  <span>CUSTOMER REVIEWS</span><br>
  <form name="checkform" onclick="productFilter()">
    <input type="checkbox" name="ratings" id="rating-checka">
    <label for="rating-checka">4 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkb">
    <label for="rating-checkb">3 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkc">
    <label for="rating-checkc">2 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkd">
    <label for="rating-checkd">1 * & Above</label>
  </form>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related