Home  >  Q&A  >  body text

How to increase the number entered?

I tried to implement the step attribute when using the HTML input element. This way I can add 100 to the current value by clicking on the up/down arrows in the input field.

However, step determines legal values, so it does not work with simple increments. For example, if I enter 123, it will increase to 200, not 223.

// populate field
document.querySelector("input").value = "123";
<input type="number" step="100" value="0"/>

Is there a simple solution for increment/decrement functions for input elements?

P粉605233764P粉605233764183 days ago274

reply all(2)I'll reply

  • P粉459440991

    P粉4594409912024-04-02 17:25:23

    const input = document.getElementById("myInput");
    const incrementBtn = document.getElementById("incrementBtn");
    const decrementBtn = document.getElementById("decrementBtn");
    
    incrementBtn.addEventListener("click", () => {
      input.stepUp(100); // Increment the input value by 1
    });
    
    decrementBtn.addEventListener("click", () => {
      input.stepDown(100); // Decrement the input value by 1
    });
    <input id="myInput" type="number" value="123" min="0" step="1" />
    <button id="incrementBtn">Increment</button>
    <button id="decrementBtn">Decrement</button>

    In the callback function, we use the built-in methods stepUp() and stepDown() to increment and decrement the input value by 100 respectively. These methods ensure that input values ​​are modified correctly regardless of step properties.

    reply
    0
  • P粉138871485

    P粉1388714852024-04-02 09:04:37

    step Push away attribute:

    const input = document.querySelector('input');
    input.value = 123;
    input.setAttribute('value', 123);
    <input type="number" step="100">

    reply
    0
  • Cancelreply