1. Problem
Hello everybody
Every time I press a button it must add 1 to the value found in the input box
The problem is that every time I press the button instead of adding +1 to the value, it concatenates the value like it is a string
Expected result after clicking on the button 5 times:
JavaScript
x
2
1
5
2
What is actually happening:
JavaScript
1
2
1
11111
2
2. Code
JavaScript
1
4
1
// the html
2
<button id="add-one">+</button>
3
<input type="text" value="" id="output-box"/>
4
JavaScript
1
8
1
// the javascript
2
document
3
.getElementById("add-one")
4
.addEventListener("click", function () {
5
document.getElementById("output-box").value += parseInt(1);
6
});
7
8
please help 🙁
Advertisement
Answer
An input.value
will always return a string. So in order to subtract the value you need to convert it into a number first:
JavaScript
1
13
13
1
const setup = () => {
2
3
document
4
.getElementById("add-one")
5
.addEventListener("click", () => {
6
const outputBox = document.getElementById("output-box");
7
outputBox.value = +outputBox.value + 1;
8
});
9
10
11
};
12
13
window.addEventListener('load', setup);
JavaScript
1
2
1
<button id="add-one">+</button>
2
<input type="number" id="output-box">