0

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>

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It also worked when I simply removed 'else' from my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.