Javascript表单验证总计100

时间:2016-07-27 18:40:14

标签: javascript validation

我需要验证下面的表格,以确保所有输入的总数正好是100而且只有数字。到目前为止,我可以验证它是否超过100但是当我尝试验证是否低于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 个答案:

答案 0 :(得分: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')