Yufei Liu Yufei Liu - 1 year ago 106
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!

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

function adder(a,b){

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

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



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

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


Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download