简体   繁体   English

从输入中求和并从总计中减去

[英]Sum values from inputs and subtract from total

The point is that you can enter values in the fields, and the final result is obtained by subtracting from 100重点是可以在字段中输入值,最后的结果是从100中减去

 function findTotal() { var arr = document.getElementsByClassName('injection-dist'); var tot = document.getElementById('total').value; var sum = 0; for (var i = 0; i < arr.length; i++) { if (parseInt(arr[i].value)) { sum += parseInt(arr[i].value); } } final = tot - sum; document.getElementById('total').value = final; }
 Qty1: <input onblur="findTotal()" type="text" class="injection-dist" name="qty[]" id="qty1" /><br> Qty2: <input onblur="findTotal()" type="text" class="injection-dist" name="qty[]" id="qty2" /><br> Qty3: <input onblur="findTotal()" type="text" class="injection-dist" name="qty[]" id="qty3" /><br> Qty4: <input onblur="findTotal()" type="text" class="injection-dist" name="qty[]" id="qty4" /><br> <br><br> Total: <input type="text" name="total" id="total" value="100" />

The code works, but only when entering a single value.该代码有效,但仅在输入单个值时有效。 When entering a second value, some recalculation is done and the result is incorrect输入第二个值时,会进行一些重新计算,结果不正确

For example, if we enter a value of 1 in a field, we get 99, but when we enter a subsequent value of 2 in another field, we get 96 instead of 97...例如,如果我们在一个字段中输入值 1,我们会得到 99,但是当我们在另一个字段中输入后续值 2 时,我们会得到 96 而不是 97...

Thanks if anyone can help谢谢如果有人可以帮助

I've removed the function that you had, since it was getting the value of all input fields at the same tame, and then basically doing total - SumOfAllInputs each time you change a value.我已经删除了您拥有的 function,因为它以相同的方式获取所有输入字段的值,然后基本上在每次更改值时进行total - SumOfAllInputs

Instead, I created a list of all inputs, and added the change event for each of them, that gets the value ONLY of the one that is currently changed, and then do total - thatValue .相反,我创建了所有输入的列表,并为每个输入添加了change事件,该事件获取当前更改的值,然后执行total - thatValue

 var qty = document.querySelectorAll(".injection-dist"); //NodeList of all input fields qty.forEach(function(item){ //iterate trough the list item.addEventListener("change", function(){ // add change event for each of the elements (instead of onBlur) var value = item.value; //get value of the inserted value document.getElementById('total').value -= value;}); //change total value })
 Qty1: <input type="text" class="injection-dist" name="qty[]" id="qty1"/><br> Qty2: <input type="text" class="injection-dist" name="qty[]" id="qty2"/><br> Qty3: <input type="text" class="injection-dist" name="qty[]" id="qty3"/><br> Qty4: <input type="text" class="injection-dist" name="qty[]" id="qty4"/><br> <br><br> Total: <input type="text" name="total" id="total" value="100" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM