+ 2

Can somebody help me up with this code?

<!DOCTYPE html> <body> <input type="text" id="input2"> <input type="text" id="input" > <input type="text" id="result"> <button onclick="Calculate()">Calculate</button> <script> var a = document.getElementById("input2"); var b = document.getElementById("input"); var c = a + b; function Calculate() { c.value = document.getElementById("input").value; }; </script> </body>

30th Oct 2016, 10:05 PM
Tomaž Roblek
Tomaž Roblek - avatar
2 Réponses
+ 3
You should include the code where You get the values inside the input so You can get the values of the input when You click and not the values of the inputs as soon as the page loads. <!DOCTYPE html> <body> <input type="text" id="input2"> <input type="text" id="input" > <input type="text" id="result"> <button onclick="Calculate()">Calculate</button> <script> function Calculate() { var a = document.getElementById("input2").value; var b = document.getElementById("input").value; var c = parseInt( a )+ parseInt( b ); document.getElementById("result").value = c; }; </script> </body> also Since the input values are string You have to parse them to int un order to do the math. that should work.
30th Oct 2016, 11:47 PM
Esteban Juarez Rodriguez
Esteban Juarez Rodriguez - avatar
0
you should change the type of the data value: string -> number "1" + "2"; // "12" 1 + 2 ; // 3 parseInt("98") + 1; // 99
12th Nov 2016, 11:31 PM
Pytness
Pytness - avatar