2015-02-06 69 views
0

我寫了一個jquery腳本,該腳本不工作。輸入金額時需要計算服務稅。例如金額100和服務稅2%。總金額應該自動來。我寫了一個函數,onchange caltax()寫在金額字段。這裏是我的腳本function caltax() var am=$('#amount').val(); var ta=$('#tax1per').val(); var total=(am*ta)/100; $('#tax1').val(total); };如何在輸入金額時計算服務稅

回答

1

你應該在jQuery中使用on input方法。以下是如何做到這一點:

$("#tax1per, #amount").on('input', function(){ 
 
    var am = $('#amount').val(); 
 
    var ta = $('#tax1per').val(); 
 
    var total = (am * ta)/100; 
 
    $('#tax1').html(total); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
Amount: <input type="text" id="amount"> 
 
<br><br> 
 
Perc: <input type="text" id="tax1per"> 
 
<br><hr> 
 
Result: <span id="tax1"></span>

這裏的JSFiddle

+0

嗨,我應該在金額字段上寫onchange函數,因爲寫入時它不會更改值 – THOMAS 2015-02-06 11:39:09

+0

我已經使用上面的代碼,它不能正常工作。任何想法爲什麼? – THOMAS 2015-02-06 11:59:34

+0

在這種情況下,請在您的問題中添加更多相關代碼。從你問的問題,我建議的代碼解決了目的。順便說一下,'onchange'函數用於''元素。完全按照我的建議來做,它應該可以工作。 – Preetesh 2015-02-06 12:45:52