更新时间:2023-02-10 19:56:18
将var $inst = $('.inst_amount');
移至使用位置:var total = 0,$inst = $('.inst_amount');
-实际上甚至没有.查看我的代码
move var $inst = $('.inst_amount');
to where you use it:var total = 0,$inst = $('.inst_amount');
- actually don't even. See my code
使用逗号分隔变量
干-不要重复自己
正确提供该类,然后将该字段添加到容器中.
give the class correctly and add the field to a container.
function sumIt() {
var total = 0, val;
$('.inst_amount').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('#total_price').html(Math.round(total));
$('#total_amount').val(Math.round(total));
}
$(function() {
// $('.datepicker').datepicker(); // not needed for this test
$("#add").on("click", function() {
$("#container input").last()
.before($("<input />").prop("class","inst_amount").val(0))
.before("<br/>");
sumIt();
});
$(document).on('input', '.inst_amount', sumIt);
sumIt() // run when loading
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
<input type="text" class="inst_amount" value="4" /><br/>
<input type="text" class="inst_amount" value="" /><br/>
<input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span>