使用Javascript填充具有相同数据的2个字段

时间:2013-04-02 19:22:01

标签: javascript

我有一个表单字段,x_amount,填充了一个静态编号,基于下拉列表中的选择,由于某种原因,它作为x_ship_to_address来到我身边。如果选择1或2,则x_amount用25或45进行包装。如果选择3或4,则用户在payment_mount中输入值,然后x_amount变为payment_amount x 1.03。我想,如果用户选择1或2,则payment_amount和x_amount都填充为25或45.这是JS正在使用静态编号填充x_amount:

function SI_money(amount) {
    // makes sure that there is a 0 in the ones column when appropriate
    // and rounds for to account for poor Netscape behaviors 
    amount=(Math.round(amount*100))/100;
    return (amount==Math.floor(amount))?amount+'.00':((amount*10==Math.floor(amount*10))?amount+'0':amount);
}

function calcTotal(){
var total = document.getElementById('x_amount');
var amount = document.getElementById('payment_amount');
var payment = document.getElementById('x_ship_to_address');

if( payment.selectedIndex == 0)
    total.value = 'select Type of Payment from dropdown';
else if( payment.selectedIndex == 3 || payment.selectedIndex == 4 )
    total.value = SI_money(parseFloat(amount.value * 1.03));
else if( payment.selectedIndex == 1 )
    total.value && amount.value = SI_money(25.00);
else if( payment.selectedIndex == 2 )
    total.value = SI_money(45.00);
}

我想我希望calcTotal的最后两个if是这样的:

else if( payment.selectedIndex == 1 )
    total.value && amount.value = SI_money(25.00);
else if( payment.selectedIndex == 2 )
    total.value && amount.value = SI_money(45.00);

但添加&&抛出错误。我想我只是遗漏了一些关于语法的东西 - 我怎么说两个字段都填充了正确的静态数字?

1 个答案:

答案 0 :(得分:1)

&&并不意味着“做这个和那个”。您需要单独执行这些:

total.value && amount.value = SI_money(25.00); <-- wrong

正确:

total.value = SI_money(25.00);
amount.value = SI_money(25.00);

另外你真的需要阅读:Code Conventions for the JavaScript Programming Language。您的代码中有大量可疑的大括号。