Skip to content
Advertisement

Sum value within a every time I press a button

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:

5

What is actually happening:

11111

2. Code

// the html
<button id="add-one">+</button>
<input type="text" value="" id="output-box"/>
// the javascript
document
  .getElementById("add-one")
  .addEventListener("click", function () {
    document.getElementById("output-box").value += parseInt(1);
  });

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:

const setup = () => {

  document
    .getElementById("add-one")
    .addEventListener("click", () => {
       const outputBox = document.getElementById("output-box");
       outputBox.value = +outputBox.value + 1;
  });


};

window.addEventListener('load', setup);
<button id="add-one">+</button>
<input type="number" id="output-box">
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement