2013-04-02 34 views
-1

我有一個表單字段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,那麼這兩個支付金額和x_amount被填充了25或45.這是工作來填充x_amount與靜態數量的JS:用相同的數據填充2個字段,使用Javascript

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的最後兩個IFS是這樣的:

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

&&並不意味着「做這個和那個」。您需要單獨執行這些:

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。你的代碼中有一些可疑的花括號。

+0

好 - 這是一個簡單的修復。感謝您的鏈接,我在每個陳述中添加了大括號。 – Lauren

+0

@Diodeus total.value = amount.value = SI_money(25.00); ?在這裏有任何類似不好的練習(雖然我從來沒有這樣寫過) – hop

+0

你可以做到這一點,但你不能沿着範圍來確定變量的範圍,所以我通常會避免使用id。參見:http://stackoverflow.com/questions/1758576/multiple-left-hand-assignment-with-javascript –

相關問題