[英]I cannot find why this simple JS isn't working. (Sales Tax Calculator)
我的HTML是一個簡單的輸入表單,如下所示:
<div id="taxCalc">
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" >
<span id="subtotal_message">Enter order subtotal</span><br />
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" >
<span id="tax_rate_message">Enter sales tax rate (99.9)</span><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br />
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" onclick="calculate_click()">
<input type="button" id="clear" value="Clear" onclick="clear_click()">
我的JS是2個簡單的函數...
var subtotal, taxRate, salesTax, total;
function setValues() {
subtotal = document.getElementById("subtotal").value;
taxRate = document.getElementById("tax_rate").value;
salesTax = document.getElementById("sales_tax").value;
total = document.getElementById("total").value;
}
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
我還包括了JS Fiddle鏈接,以獲取更多信息: http : //jsfiddle.net/tjhillard/nkHxe/1/當單擊“計算”按鈕時,我希望在相應的字段中顯示營業稅和總計。
預先感謝您的幫助!
您只需要更新回值即可:
改變這個:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
成:
function calculate_click() {
setValues();
salesTax = (subtotal * taxRate) / 100;
total = subtotal + salesTax;
// place the value in the form
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
您的代碼的更新版本: http : //jsfiddle.net/nkHxe/4/
應該采用以下方式:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
PS請記住,您的代碼是錯誤組織的))
1)您不回寫值。 Maxim和Balexandre已經展示了方法。
2) total
是一個字符串與一個數字的連接,該數字又導致一個字符串。 Maxim和Balexandre尚未解決此問題。
通過直接從輸入字段讀取,可以返回字符串。 因此,首先將它們解析為數字。 例:
parseInt(document.getElementById("subtotal").value)
在您的代碼中,如上所述存在計算total
時的問題。 對於salesTax
不會發生此問題,因為salesTax
您應用的數學運算,字符串將自動轉換。
希望這可以幫助。
已更新,已完全正常運行,總代碼已修復將整數作為字符串傳遞(串聯)的問題。
添加了代碼 ,
subtotal = parseInt(document.getElementById("subtotal").value)
total = parseInt(document.getElementById("total").value)
鏈接 , http://jsfiddle.net/nkHxe/150/
感謝TJH,Balexandre,Maxim和Patrick :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.