Yufei Liu Yufei Liu - 3 months ago 8
HTML Question

HTML and Javascript (Adding )

I'm trying to write a simple calculator by html and JavaScript, however the result of 2+2 is not 4 but 22, please help me with this problem!
Thanks!

<html>
<body>
<input type ="text" id ="x">
<p> + </p>
<input type ="text" id ="y">

<script>
function adder(a,b){

var x = document.getElementById("x").value;
var y = document.getElementById("y").value;

document.getElementById("demo").innerHTML = x+y;


}

</script>

<button type = "button" onclick = "adder(x,y)"> calculate </button>

<p id = "demo"> </p>

</body>
</html>

Answer

Slightly adding to ASDFGerte's answer you need to convert the elements x and y to integers because get element by id returns a string to do this you can use the parseint function

var x = parseInt(document.getElementById("x").value);
var y = parseInt(document.getElementById("y").value);
Comments