Home > front end >  HTML `<input type="number">` element - Customize increment value of arrow buttons in
HTML `<input type="number">` element - Customize increment value of arrow buttons in

Time:06-25

I have an HTML <input> element with type="number":

Number Input

I want to use a step value of 1. That is, any integer is allowed. However, I would also like the arrow buttons to increment/decrement the value of the input by some value, for example, 5. Is this possible?

From the MDN docs, I can't find a way to accomplish this using HTML alone. I would also accept an answer involving intercepting the input event using javascript to change the value of the input, but I don't know of a way to distinguish between a change due to keypresses vs. a change due to clicking the arrow buttons.

CodePudding user response:

You can always capture the input in javascript and convert the values to an integer with parseInt and use the normal step to control the arrow stepping.

With this method you don't have to worry about distinguishing between the stepping and input as the steps will already be integers anyway.

let nums = document.querySelectorAll("input[type='number']");

nums.forEach(function(e){
  e.addEventListener("input",function(el){
    el.target.value = parseInt(el.target.value)    
  });
});
<input type="number" step="4" />

CodePudding user response:

Currently it is not possible to capture a click on the spinners directly, but there are some ways to detect a click on them.

By using different events it is possible to adjust the step size for the moment. But it may cause some unwanted effect if the user uses the mouse to click on a spinner, keeps the mousekey pressed and presses an arrow key up/down:

// fires ones right before the value is changed for the first time
input.addEventListener("mousedown", ({ target }) => target.setAttribute("step", 5));
// fires after release of the mouse key, even if the user moved the mouse
input.addEventListener("change", ({ target }) => target.setAttribute("step", 1));
<input id="input" type="number" step="1" value="0" />

  • Related