简体   繁体   English

如何验证 JavaScript 中的多个复选框?

[英]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.我有 4 个复选框,我想在前两个被选中但没有收到 output 时显示不同的警报。请让我知道哪里出错了。

 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 1)您必须验证选中的每个复选框,因此您可以创建一个 function productFilter并且每次您选中它都会运行

2) You have to check for 0 and 1 index checkbox first than only 0 . 2)您必须首先检查01索引复选框,而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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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