Baern Ungart
Baern Ungart

Reputation: 3

Sum value within a <input> 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 :(

Upvotes: 0

Views: 1050

Answers (3)

GetSet
GetSet

Reputation: 1577

Try:

// the javascript
document
  .getElementById("add-one")
  .addEventListener("click", function () {
    let el = document.getElementById("output-box");
    // let v = parseInt(el.value) // wrong
    // per comments @PaulRooney, instead when parsing empty string returns Nan
    // so instead use:
    let v = parseInt(el.value) || 0
    el.value = v + 1
    
  });

In this way you parse the original value to an int before adding 1.

Upvotes: 0

Andre Kardec
Andre Kardec

Reputation: 11

There are two problems with your code. First, you're passing '1' all the times without incrementing. The second one is because you're using the addition assignment operator (+=) and this is adding the value that you're passing sequentially as <input type="text" value="" id="output-box"/> is a string type. So, try this code out. This should fix it.

        // the javascript
        let i = 1;
        document
        .getElementById("add-one")
        .addEventListener("click", function () {
            document.getElementById("output-box").value = i++;
        });

Upvotes: 0

Jens Ingels
Jens Ingels

Reputation: 816

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">

Upvotes: 1

Related Questions