2 回答

TA貢獻1847條經驗 獲得超11個贊
試試這個:
function calcTotal() {
// remove $ sign and parse Float price
var price = parseFloat(document.getElementById("price").value.substr(1));
// parse float quantity
var quantity = parseFloat(document.getElementById("quantity").value);
var total = price * quantity;
//pass calculated value to input with id total
document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">

TA貢獻1883條經驗 獲得超3個贊
任何涉及字符串的操作都會返回 ,但是您應該強制輸入值NaNNumber
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total =Number(price) * Number(quantity);
console.log(total);
}
使用數字與解析浮動
因此,只要您有標準的數字輸入,就沒有區別。但是,如果您的輸入以數字開頭,然后包含其他字符,parseFloat 會將數字從字符串中截斷,而數字則給出 NaN(不是數字):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
添加回答
舉報