我想在我的if语句中使用else语句的sub_total和tax_amount变量的定义值来加值。
if (field_name == 'amtdelivary') {
var delivary_element = document.getElementById("amtdelivary");
var delivary_value = delivary_element.options[delivary_element.selectedIndex].value;
var grand_total = document.getElementById("fnltot").value;
grand_total = sub_total + tax_amount + delivary_value;
} else {
var sub_total = 0;
运行循环来计算所有行
for(i=1;i<6;i++)
{
将所有行合计累加到总计
row_total = "total" + i;
sub_total = sub_total +parseFloat(document.getElementById(row_total).value);
}
var tax_amount= (sub_total*0.07);
var tax_amount = Math.round(tax_amount);
$('#amttax').val(tax_amount);
$('#subtotal').val(sub_total); // sub total total
grand_total= (sub_total + tax_amount);
$('#fnltot').val(grand_total);
}
只有if/else
的一部分被执行。 只需将grand_total=(sub_total+tax_amount);
移动到您的if
:
var grand_total = (sub_total + tax_amount);
if (field_name == 'amtdelivary') {
var delivary_element = document.getElementById("amtdelivary");
var delivary_value = delivary_element.options[delivary_element.selectedIndex].value;
// Makes no sense to immediately overwrite it
// var grand_total = document.getElementById("fnltot").value;
grand_total += delivary_value;
} else {
$('#fnltot').val(grand_total);
}
注意,两个if/else块中的grand_total变量都被覆盖。
因此,只要在if/else块之外声明变量并在需要的地方为其赋值,它就可以工作! 请尝试以下解决方案:
var grand_total = 0;
if (field_name == 'amtdelivary') {
var delivary_element = document.getElementById("amtdelivary");
var delivary_value = delivary_element.options[delivary_element.selectedIndex].value;
grand_total = sub_total + tax_amount + delivary_value;
} else {
grand_total = (sub_total + tax_amount);
$('#fnltot').val(grand_total);
}