2016-07-27 31 views
0

我需要驗證下面的表單以確保所有輸入的總數完全是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> 
+0

兩種方法可以防止這種情況發生:1。在findTotal()'是退出函數如果有的話'qty'輸入爲空的'開始放入if語句。 2. findTotal()從一個按鈕點擊運行,您可以在輸入所有'qty'後點擊。 – neilsimp1

+0

謝謝,是的,我想到了選項2,但它不是最佳選擇。我認爲選項1不起作用,因爲隨着用戶輸入值,findTotal()會添加每個值。在計算時會有空值 – invincibleme

+0

在這種情況下,只需在循環並設置標誌時檢查是否有任何輸入爲空。如果標誌爲真,返回/不要調用'alert()' – neilsimp1

回答

0
let total = [...document 
    .getElementById('form1') 
    .querySelectorAll('input')] 
    .reduce((acc, el) => acc += parseInt(el.value, 10), 0) 

if (total !== 100) 
    return console.warn('total inputs not 100') 
+0

我會替換「document.getElementById('total')。value = tot; //檢查權重分數= 100 如果(TOT> 100){ 警報( 「請確保數總計100」); document.getElementByName( 「數量」)值= NULL; 返回FALSE; }」與你有什麼上面? – invincibleme

+1

儘管這段代碼可能會解決這個問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ