2017-04-17 76 views
0

我是新來的java腳本,我有三個文本字段與ID分別爲文本1,文本2,文本3。我想輸入其中2個值並在第三個中輸出總和。如何在Java腳本函數中傳遞文本字段值?

我的代碼看起來像這樣,請告訴我,我做錯了什麼。 它將它們添加爲字符串而不是數字。

另外我想說,如果我在三個框中的任意兩個中輸入值。另一個調整自己。 EX:'__'+ 5 = 7 =>'2'+ 5 = 7
如果我將變量放在值屬性中,它會起作用。如果那麼那麼如何?

<html> 
 

 
<head> 
 
    <script> 
 
    function myCalculator(a, b) { 
 
     c = a + b; 
 
     document.getElementById("text3").value = c; 
 
    } 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <p> 
 
    <h1>Calculator</h1> 
 
    <input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input> 
 
    <input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input> 
 
    </p> 
 

 
</body> 
 

 
</html>

+0

你可能想看看[parseFloat(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat),根據您的要求。 – Xotic750

回答

0

你需要調用myCalculator函數的兩個參數parseInt(text)他們先轉換爲數字。

function myCalculator(a,b){ 
    a = parseInt(a, 10); // convert to integer first 
    b = parseInt(b, 10); 

    c=a+b; 
    document.getElementById("text3").value = c; 
} 

parseInt功能的第二個參數是基數,其需要爲10讀取在十進制數字。 ES5默認爲10。

+0

使用[parseInt](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt) – Xotic750

+0

時,指定'radix'總是明智的。謝謝,這工作。 但parsInt()和Number()之間的概念區別是什麼 –

+0

'Number'是對象封裝,請參閱(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number ),'parseInt'是從字符串中讀取數字的本地函數。 –

0

使用Number()將字符串轉換爲數字。文本input.value中的任何內容最初都是一個字符串。

function myCalculator(a, b) { 
    var c = Number(a) + Number(b); 
    document.getElementById("text3").value = c; 
} 
0

取代您與文本塊碼,首先記得字符串添加前引號和第二格式的值傳遞ID爲JavaScript。

<html> 
    <head> 
    <script> 
    function myCalculator(a,b){ 
    var c=parseInt(a)+parseInt(b); 
    document.getElementById('text3').value = c; 
    } 
    </script> 
    </head> 
    <body> 

    <p> 
    <h1>Calculator</h1> 
    <input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input> 
    <input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input> 
    </p> 

    </body> 
    </html> 
相關問題