0

I have an issue with input fields. I have 2 input field type="number" and I would just like to add those 2 number together. My input fields

<input type="number" name="a" id="a" onchange="add()">
<input type="number" name="b" id="b" onchange="add()">

This is my js file

function add() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = a + b;
}

Issue is when I try 20+20 result is 2020, not 40 as I would expect.

Tom
  • 3
  • 2

2 Answers2

1

You can use the parseInt() function to convert the string to an integer

cagcoach
  • 625
  • 7
  • 24
0

as stated in the comment, all values from inputs are strings, so you need to

function add() {
var a = parseInt(document.getElementById("a").value);
var b = parseInt(document.getElementById("b").value);
var c = a + b;
}
LostJon
  • 2,287
  • 11
  • 20