我正在尝试制作一个自动聚合数字并动态添加输入的应用。当我删除任何输入字段时,该数字不会从总和中减去。如何从我删除的条目中减去数字?感谢您的帮助。
var sayac = 1;
$(function() {
$('#ekle').click(function() {
sayac += 1;
$('#ekhizmetler tbody').append(
'<tr><th><strong></strong></th><td><input id="alan_" name="alanlar2[]' + '" type="text" class="form-control inst_amount" /></td><td><a href="#"class="delete btn btn-danger">Delete</a></td></tr>');
});
$('#ekhizmetler').on("click", ".delete", function(e) {
e.preventDefault();
$(this).closest("tr").remove();
})
});
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() {
$("#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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<table id="ekhizmetler" class="table table-condensed">
<thead>
<tr>
<th>Sıra</th>
<th>Numbers</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<th><strong>1</strong></th>
<td><input id="alan_2" name="alanlar2[]" type="text" class="form-control inst_amount"></td>
<td><input id="total_amount" name="total_amount" type="text" class="form-control" value="0"></td>
<td><a href="#" class="delete btn btn-danger">Delete</a></td>
</tr>
</tbody>
<tfoot>
<td>
<p id="ekle"><a href="#ekle" class="btn btn-primary">» New Field </a></p>
</td>
</tfoot>
</table>
</div>
答案 0 :(得分:0)
就像单击sumIt
按钮时所做的add
一样,在执行删除操作时通过求和来从总和中减去。
$('#ekhizmetler').on("click", ".delete", function(e) {
e.preventDefault();
curr_val = $(this).closest("tr").val(); # get value of box to be deleted
total_val = $("#total_amount").val(); # get total value
$("#total_amount").val(total_val-curr_val); # set new total
$(this).closest("tr").remove()
})