今天有一道关于用js求和的题
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty1 : <input class="txt" type="number" name="qty" id="qty1"/><br>
Qty2 : <input class="txt" type="number" name="qty" id="qty2"/><br>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/><br>
Qty4 : <input class="txt" type="number" name="qty" id="qty4"/><br>
Qty5 : <input class="txt" type="number" name="qty" id="qty5"/><br>
Qty6 : <input class="txt" type="number" name="qty" id="qty6"/><br>
Qty7 : <input class="txt" type="number" name="qty" id="qty7"/><br>
Qty8 : <input class="txt" type="number" name="qty" id="qty8"/><br>
<br><br>
Total : <span id="sum">0</span><br>
此代码仅在我直接在输入字段中输入数字时有效。但是,当我单击输入字段中的上下箭头时,js 代码似乎不起作用。我该如何解决? 谢谢!
最佳答案
使用箭头符号更改元素值时 change事件被触发。
尝试使用 input
而不是 keyup事件。
The input event fires when the value of an
<input>
,<select>
, or<textarea>
element has been changed.
变化:
$(this).keyup(function(){
收件人:
$(this).on('input',function(){
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).on('input',function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty1 : <input class="txt" type="number" name="qty" id="qty1"/><br>
Qty2 : <input class="txt" type="number" name="qty" id="qty2"/><br>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/><br>
Qty4 : <input class="txt" type="number" name="qty" id="qty4"/><br>
Qty5 : <input class="txt" type="number" name="qty" id="qty5"/><br>
Qty6 : <input class="txt" type="number" name="qty" id="qty6"/><br>
Qty7 : <input class="txt" type="number" name="qty" id="qty7"/><br>
Qty8 : <input class="txt" type="number" name="qty" id="qty8"/><br>
<br><br>
Total : <span id="sum">0</span><br>
关于javascript - 通过javascript从数字类型输入字段计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59133114/