我需要驗證下面的表單以確保所有輸入的總數完全是100,並且只有數字。到目前爲止,我可以驗證它是否超過100.但是當我嘗試驗證是否低於100時,我會在輸入所有值之前得到警報。Javascript表單驗證總數100
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" class="hvr-pop"/> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" class="hvr-pop"/> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" class="hvr-pop"/> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" class="hvr-pop"/> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" class="hvr-pop"/><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" class="hvr-pop"/><br>
<textarea type="text" name="total" id="total" class="hvr-pop" readonly placeholder="Must total 100"></textarea>
</form>
<script>
function findTotal(){
"use strict";
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0; i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
}
document.getElementById('total').value = tot;
// check that weightage scores = 100
if (tot > 100) {
alert("Please make sure numbers total 100");
document.getElementByName("qty").value = null;
return false;
}
}
<script>
兩種方法可以防止這種情況發生:1。在findTotal()'是退出函數如果有的話'qty'輸入爲空的'開始放入if語句。 2. findTotal()從一個按鈕點擊運行,您可以在輸入所有'qty'後點擊。 – neilsimp1
謝謝,是的,我想到了選項2,但它不是最佳選擇。我認爲選項1不起作用,因爲隨着用戶輸入值,findTotal()會添加每個值。在計算時會有空值 – invincibleme
在這種情況下,只需在循環並設置標誌時檢查是否有任何輸入爲空。如果標誌爲真,返回/不要調用'alert()' – neilsimp1