2

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?

5
  • 3
    step is not just increments, it also implies that values must be a multiple of step. Commented Jun 14, 2023 at 20:41
  • 1
    Should be easy enough to write a function that increments/decrements by the step you want without using the step attribute Commented Jun 14, 2023 at 20:42
  • @fordat How would that help? Commented Jun 14, 2023 at 20:43
  • @Barmar you are correct, step determines legal values. Commented Jun 14, 2023 at 20:44
  • @j08691 I was wondering if writing a increment function would be unnecessary Commented Jun 14, 2023 at 20:45

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

5 Comments

Don't just post code, explain what was wrong and how you fixed it.
Specifically, it's based on the initial value attribute.
@Barmar sorry, I'll write the code first, then I'll explain. But it seems so clear if setAttribute is specified. With best regards.
The initial value is the defaultValue property. No need to use setAttribute.
Yes, defaultValue also works. I'll add that to my answer if you don't mind.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.