Cannon Moyer
Cannon Moyer

Reputation: 3174

Increment HTML5 Number Field by .5 with step of .01

I've got a number field that I use as a quantity value and I need values of the following format to be accepted by the field.

0.01
0.1
1

So I created my input field like so:

<input type="number" step=".01">

The arrows to the right of the field and the up/down keyboard buttons increment the value by .01. However, I need to maintain this precision but when the user clicks the up/down arrow or presses the up/down keys, I want the field to increment/decrement by .5 which is the more standard use case.

I did have this working with a jQuery listener on input, but that also caused problems when I directly typed in the value since the listener was fired then as well.

Upvotes: 1

Views: 7524

Answers (2)

Basically, you need to change its set value property between:

<input type="number" step=".01">

and

<input type="number" step=".5"> When the user clicks the up/down arrow or presses the up/down keys.

So, I've made an example in JavaScript to illustrate this particular scenario.

Something like this:

(function() {
  var numberFields = document.querySelectorAll("input[type=number]"),
    len = numberFields.length,
    numberField = null;

  for (var i = 0; i < len; i++) {
    numberField = numberFields[i];
    numberField.onclick = function() {
      this.setAttribute("step", ".5");
    };
    numberField.onkeyup = function(e) {
      if (e.keyCode === 38 || e.keyCode === 40) {
        this.setAttribute("step", ".01");
      }
    };
  }
}());
<input type="number" step=".01">

Upvotes: 6

yaakov
yaakov

Reputation: 4675

You can't do this with an number input, but with a text input, the magic happens...

I've styled it a bit so you can see when it's valid and invalid.

It is possible to use negative numbers in here, so if you want that I can edit it, but it gets a little wacky around -1 to 0.

let input = document.getElementById('addNum');
increment = 0.5;

input.onkeydown = function(e){
  if(e.key == "ArrowUp"){
    e.preventDefault();
    let value = +this.value;
    this.value = value + increment;
  } else if(e.key == "ArrowDown"){
    e.preventDefault();
    let value = +this.value;
    this.value = value - increment;
  }
}
input:valid {
  border-color: #0f0;
}
input:invalid {
  border-color: #f00;
}
input {
  outline: none;
}
Enter a (non-negative) number:
<input type="text" pattern="\d*[.]*\d{0,3}" id="addNum">

Upvotes: 1

Related Questions