2016-09-07 60 views
-2

我有一個表格,用戶可以輸入零件號碼,零件價格和數量。然後它的倍數是價格和數量,以獲得總數。我把這部分開始運行起來。簡單的數學,但它不工作?

現在我已經得到了部分稅收,然後總計但是這是即時得到:

function calculateit() { 
    var myBox1 = $('input[name=tax2]:checked').val(); //taxes value 
    var myBox2 = document.getElementById('partstotalvalue').value; //parts total value 
    var result = document.getElementById('partstax'); // input field for the total of taxes * parts 
    var myResult = myBox1 * myBox2; //result = taxes * parts total 
    result.value = myResult; // display the results 

    var result2 = document.getElementById('partstotalwithtax'); // inputp field for taxes + total value 
    var totalResult = myResult + myBox2; // totalresult = taxes on part + the parts total 
    result2.value = totalResult; // display the results 
} 

screenshot

這裏的小提琴:

https://jsfiddle.net/jdarville/hxqev0be/

+2

看起來你正在嘗試添加字符串而不是數字。 –

+2

僅供參考,當您從DOM中讀取值時,它們被讀作字符串而不是數字。您將不得不使用'parseFloat'或'parseInt'手動將其解析爲數字。另外,'+'運算符也是字符串的concatination運算符 – Rajesh

+1

你能給我一個小提琴嗎? –

回答

3

+運算符和變量類型的問題。

你的情況,你嘗試添加字符串這樣

var a = "1" + "2"; <- 12 

你需要的是使用ParseFloat,然後做數學

var a = parseFloat("2") + parseFloat("2.14") <- 4.14 

希望這有助於。

0

您可以使用unary + operator來鑄造數字。

var myBox1 = +$('input[name=tax2]:checked').val(); //taxes value 
var myBox2 = +document.getElementById('partstotalvalue').value; //parts total 
+2

你不應該回答一個明顯重複的問題。 – Rajesh

+0

你爲什麼討厭? – JCD

+0

@JCD - 這裏沒有恨。只是陳述事實。 –