我有一个表格,当用户输入数字时,我需要对某些数字字段执行一些计算。我为表单创建了HTML,到目前为止,我已经有了下面的JavaScript代码,但是它不起作用。
jQuery(function($) {
// define the variables for fields
var child1 = $('pdb-male').val();
var child2 = $('pdb-female').val();
var child3 = $('pdb-unknown_sex').val();
var value = child1 + child2 + child3;
var result = $('pdb-number');
// set listener on male field
child1.on('keyup', function() {
// do the calculation and output the result on the field
result.val(value);
});
// set listener on female field
child2.on('keyup', function() {
// do the calculation and output the result on the field
result.val(value);
});
// set listener on unknown_sex field
child3.on('keyup', function() {
// do the calculation and output the result on the field
result.val(value);
});
// set the trigger on fields
child1.trigger('keyup');
child2.trigger('keyup');
child3.trigger('keyup');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 0 :(得分:1)
$(function() {
$(".person").on("input", function() {
var total = 0;
$(".person").each(function() { total += +this.value })
$('#pdb-number').val(total);
}).trigger("input")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Male:<input class="person" type="text" id="pdb-male" value="" /><br/>
Female: <input class="person" type="text" id="pdb-female" value="" /><br/>
Unknown: <input class="person" type="text" id="pdb-unknown_sex" value="" /><br/>
Total: <input type="text" readonly id="pdb-number" />