我想在提交表单之前自动计算和填充总计。总计将基于我的5个输入字段。
<input type="number" name="inspection_fee">
<input type="number" name="storage_fee">
<input type="number" name="local_fee">
<input type="number" name="cert_fee">
<input type="number" name="others_fee">
<input type="number" name="total_fee">
我知道怎么做php的方式,就像我提交变量后放置变量然后完全像这样计算它。
<?php
$inspection_fee = $paymentSettings->inspection_fee;
$storage_fee = $paymentSettings->storage_fee;
$cert_fee = $paymentSettings->cert_fee;
$local_fee = $paymentSettings->local_fee;
$others_fee = $paymentSettings->others_fee;
$total_fee = $inspection_fee + $storage_fee + $cert_fee + $local_fee + $others_fee;
?>
但是在使用javascript提交之前我将如何填充总数?就像我更改检查费一样,总费用将自动调整取决于总价值。 寻求帮助。 提前谢谢。
答案 0 :(得分:5)
total_fee
中设置值(使用Array.prototype.reduce
的好机会)input
事件
const inputs = ['inspection_fee', 'storage_fee', 'local_fee', 'cert_fee', 'others_fee']
const total = document.querySelector('input[name="total_fee"]')
const sumTotal = () => {
total.value = inputs.reduce((sum, input) =>
sum += parseInt(document.querySelector(`input[name="${input}"]`).value || 0, 10), 0)
}
inputs.forEach(input => {
document.querySelector(`input[name="${input}"]`).addEventListener('input', sumTotal, false)
})
<input type="number" name="inspection_fee">
<input type="number" name="storage_fee">
<input type="number" name="local_fee">
<input type="number" name="cert_fee">
<input type="number" name="others_fee">
<input type="number" name="total_fee" readonly>
答案 1 :(得分:2)
将onblur事件附加到所有输入字段以调用JavaScript函数。我改变了名字&#34;属性为&#34; id&#34;要在JS函数中使用的属性。
<input type="number" id="inspection_fee" onblur="calculateTotalFee();">
<input type="number" id="storage_fee" onblur="calculateTotalFee();">
<input type="number" id="local_fee" onblur="calculateTotalFee();">
<input type="number" id="cert_fee" onblur="calculateTotalFee();">
<input type="number" id="others_fee" onblur="calculateTotalFee();">
<br/>
<input type="number" id="total_fee">
<script type="text/javascript">
function calculateTotalFee(){
var totalFee = 0;
var inspectionFee = document.getElementById("inspection_fee").value.trim() === "" ? 0 :
document.getElementById("inspection_fee").value.trim();
var storageFee = document.getElementById("storage_fee").value.trim() === "" ? 0 :
document.getElementById("storage_fee").value.trim();
var localFee = document.getElementById("local_fee").value.trim() === "" ? 0 :
document.getElementById("local_fee").value.trim();
var certFee = document.getElementById("cert_fee").value.trim() === "" ? 0 :
document.getElementById("cert_fee").value.trim();
var othersFee = document.getElementById("others_fee").value.trim() === "" ? 0 :
document.getElementById("others_fee").value.trim();
totalFee = parseInt(inspectionFee) + parseInt(storageFee) +
parseInt(storageFee) + parseInt(localFee) + parseInt(certFee) + parseInt(othersFee);
document.getElementById("total_fee").value = totalFee;
}
</script>