簡體   English   中英

如何對已檢查的數字或單位總和(JavaScript)進行限制(錯誤警報)?

[英]How to make limit(error alert) for checked numbers or units sum(JavaScript)?

嗨,這是我的代碼。 如何限制已檢查的數字或單位總和?

例如:如果總和≤12且≥20,則按提交按鈕時顯示錯誤日志(結果)。

 <script type="text/javascript"> function chkcontrol(j) { var sum=0; for(var i=0; i < document.form1.ckb.length; i++){ if(document.form1.ckb[i].checked){ sum = sum + parseInt(document.form1.ckb[i].value); } document.getElementById("msg").innerHTML="Sum :"+ sum; if(sum >20){ sum = sum - parseInt(document.form1.ckb[j].value); document.form1.ckb[j].checked = false ; alert("error:Total of yore choose is more than 20 units") //return false; } document.getElementById("msg").innerHTML="total units :"+ sum; } } </script> 

這應該可以解決您的問題。

 var form = document.forms.myform, elem = form.elements, inputVals = document.getElementsByClassName("inputVals"); form.onsubmit = function(event){ event.preventDefault(); var totalSum = 0; for(var i = 1; i <= inputVals.length; i++) { var input = document.getElementById("value" + i) if (input.checked) { totalSum += parseInt(input.value); } } if (totalSum < 12 || totalSum > 20) { alert("error:Total of your choise is more than 20 or less 12 units") } else { document.getElementById("msg").innerHTML="total units :" + totalSum; } } 
 .center{text-align:center;margin-top:1em;} 
 <form name="myform" actopm="/echo/html/" method="post"> <table> <tr> <th>1</th> <td><input class="inputVals" value=1 type="checkbox" id="value1" placeholder="input value"/></td> </tr> <tr> <th>2</th> <td><input class="inputVals" value=2 type="checkbox" id="value2" placeholder="input value"/></td> </tr> <tr> <th>3</th> <td><input class="inputVals" value=3 type="checkbox" id="value3" placeholder="input value"/></td> </tr> <tr> <th>4</th> <td><input class="inputVals" value=4 type="checkbox" id="value4" placeholder="input value"/></td> </tr> <tr> <th>5</th> <td><input class="inputVals" value=5 type="checkbox" id="value5" placeholder="input value"/></td> </tr> <tr> <th>6</th> <td><input class="inputVals" value=6 type="checkbox" id="value6" placeholder="input value"/></td> </tr> <tr> <th>7</th> <td><input class="inputVals" value=7 type="checkbox" id="value7" placeholder="input value"/></td> </tr> <tr> <th>8</th> <td><input class="inputVals" value=8 type="checkbox" id="value8" placeholder="input value"/></td> </tr> </table> <div class="center"> <input type="submit" value="submit"/> </div> </form> <div id="msg"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM