简体   繁体   中英

How to validate multiple checkboxes in JavaScript?

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) 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM