<input type="text" id="Count1" value="20">
<input type="text" id="Count2" value="30">
<input type="text" id="Count3" value="40">
<input type="text" id="Count4" value="50">
<input type="text" id="Count5" value="60">
<div class="inputbox" id="Sum"> ConunSUM </div>
我有多个输入,可能多达50,我应该如何使用onchange,自动求和。
也许是这样?
$(".value").on("input", function()
{
var sum = 0;
$('.value').each(function() {
sum += Number($(this).val());
});
$("#sum").html(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="value" value="20">
<input type="text" class="value" value="15">
<div class="inputbox" id="sum"></div>
您可以监听input
事件,然后将所有值相加。
$('input').on('input', function() {
$('#Sum').text(sum());
});
$('#Sum').text(sum());
function sum() {
let sum = 0;
$('input').each(function() {
let value = Number(this.value);
if (!isNaN(value)) {
sum += value;
}
});
return sum;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Count1" value="20">
<input type="text" id="Count2" value="30">
<input type="text" id="Count3" value="40">
<input type="text" id="Count4" value="50">
<input type="text" id="Count5" value="60">
<div class="inputbox" id="Sum"></div>
对于每个使用的get it求和。希望这对你有帮助。
$(document).ready(function() {
$('input').change(function() {
get_sum();
});
});
get_sum();
function get_sum() {
var sum = 0;
$("input[type='text']").each(function() {
sum += parseInt($(this).val());
});
$('.inputbox').html(sum);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Count1" value="20">
<input type="text" id="Count2" value="30">
<input type="text" id="Count3" value="40">
<input type="text" id="Count4" value="50">
<input type="text" id="Count5" value="60">
<div class="inputbox" id="Sum"> ConunSUM </div>
欢迎使用堆栈溢出,您可以将所有输入作为数字<input type="number" id="Count1" value="20">
然后使用
$('body').on('change','input[type="number"]',function () {
var sum = 0;
$.each($('input'), function (index,element) {
sum += Number($(element).val());
});
$('#Sum').text(sum);
});