skip to Main Content

When using HTML input elements I tried implementing the step attribute. This allowed me to add 100 to the current value by clicking the up/down arrows in the input field.

However, step determines legal values, so it won’t work for simple increments. For example, if I type in 123, it will increase to 200, not 223.

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

Is there an easy workaround for an increment/decrement function for the input element?

2

Answers


  1. step pushes away from the attribute:

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

    UPDATE:
    Also, as @Barmar and @SebastianSimon pointed out, you can use defaultValue:

    input.defaultValue = 123;
    
    Login or Signup to reply.
  2. 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>

    Inside the callback functions, we use the built-in methods stepUp() and stepDown() to increment and decrement the input value by 100, respectively. These methods ensure the input value is modified correctly, regardless of the step attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search