簡體   English   中英

如何驗證 JavaScript 中的多個復選框?

[英]How to validate multiple checkboxes in JavaScript?

我有 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)您必須驗證選中的每個復選框,因此您可以創建一個 function productFilter並且每次您選中它都會運行

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