根据以下答案,我编辑了帖子以提供更多详情。谢谢大家。
编辑:
这是我的代码:
if else
使用Javascript:
@foreach($amount_data as $amount)
<div class="col-sm-12">
<div class="input-checkbox">
<div class="inner"></div>
<input type="checkbox" name="items[]" value="{{$amount->amount}}" onchange="checkTotal()" />
</div>
<span>{{$amount->item_name}} - <b>{{$amount->amount}} {{$form->currency}}</b></span>
</div>
@endforeach
<br/> Total: <input type="text" size="2" name="total" value="0" />
@endif
表格信息:
<script type="text/javascript">
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
</script>
似乎不起作用。控制台没有错误。怎么了?
答案 0 :(得分:0)
由于名称
中的[],您需要使用括号表示法document.listForm["items[]"][i].checked
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
&#13;
<form name="payment-form" id="payment-form">
<input type="checkbox" name="items[]" value="2" onchange="checkTotal()" />2<br/>
<input type="checkbox" name="items[]" value="5" onchange="checkTotal()" />5<br/>
<input type="checkbox" name="items[]" value="10" onchange="checkTotal()" />10<br/>
<input type="checkbox" name="items[]" value="20" onchange="checkTotal()" />20<br/>
Total: <input type="text" size="2" name="total" value="0" />
</form>
&#13;
答案 1 :(得分:0)
function checkTotal() {
document.listForm.total.value = Array.prototype.reduce.call(
document.listForm.choice,
function (sum, el) {
return el.checked ? sum + +el.value : sum;
}, 0
);
}
&#13;
<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>
&#13;
答案 2 :(得分:0)
这是使用jQuery的答案。希望这个对你有帮助!我已将听众和功能分开,因为我相信它可以让以后更容易编辑。您可以将它们组合起来以缩短代码。
//Listener for the checkbox
$("input[name='choice']").change(function() {
sumUp();
});
//Funtion that adds the total up
function sumUp() {
var sum = 0;
$(" input[name='choice']:checked").each(function() {
sum += parseInt($(this).val());
});
$("input[name=total]").val(sum);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="listForm">
<input type="checkbox" name="choice" value="2" />2
<br/>
<input type="checkbox" name="choice" value="5" />5
<br/>
<input type="checkbox" name="choice" value="10" />10
<br/>
<input type="checkbox" name="choice" value="20" />20
<br/> Total:
<input type="text" size="2" name="total" value="0" />
</form>
&#13;