合计选中的复选框

Totalling the checked checkbox

本文关键字:复选框      更新时间:2023-09-26

现在的要求是在所有记录前面都有一个复选框。当我检查时,它必须添加该特定行id Total的Total字段,并在另一个名为Grand_Total的字段中显示合计。例如,如果我检查第一条记录id1和第三条记录id3,它必须向我显示3700.00(2500.00+120.00)的Grand_Total。实现这一点的最佳方法是什么?是javascript还是php?请帮帮我?

这就是我尝试过的。$('input').change(function(){recalcTotal();});

function recalcTotal() {
var total12 = 0;
$('input:checked').each(function() {
    total12 += $(this).data('tot'); 
});
$('#total12').html(total12);
}
</script>
<body>
 <input type='checkbox' data-tot='{$list5['margin_for']}' name='gt' id='gt'>   
 <input size='8' type='text' id='margin_for[]' name='margin_for[]' value='{$list5['margin_for']}' readonly>
<div id="total12"></div>
</body>

问题是您的函数不会在任何地方被调用。请在checkbox click上调用函数recalcTotal()。试试这个:

function recalcTotal() {
var total12 = 0;
$('input:checked').each(function() {
    total12 += $(this).data('tot'); 
});
$('#total12').val(total12);
}
$("input[type='checkbox']").on("click",function(){
  
  recalcTotal();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
 <input type='checkbox' data-tot='100' name='gt1' id='gt1'>   
 <input size='8' type='text' id='margin_for[]' name='margin_for[]' value='100' readonly>
  
  <input type='checkbox' data-tot='50' name='gt' id='gt'>   
 <input size='8' type='text' id='margin_for[]' name='margin_for[]' value='50' readonly>
  <input name="grandTotal" id="total12" readonly/>
</body>