alessadro alessadro - 1 year ago 206
jQuery Question

How to override HTML5 input number step function? Using jQuery

I want to change the step on the HTML5 number inputs of my webapp. I want 100 by 100 instead 1 by 1.

I have tried this:

if (e.keyCode == 38) // Arrow-Up
$(this).val(parseInt($(this).val() + 100));
if (e.keyCode == 40) // Arrow-Down
$(this).val(parseInt($(this).val() - 100));

But didn't work. How can I achieve this?

Answer Source

Change the step property on the element itself:

<input type="number" step="100" />

Or if you can't modify the HTML directly, you can do this with jQuery's attr method:

$("#mynumberinput").attr('step', 100);

Seems the actual problem is that you want to allow the user to enter a number and then have it increase or decrease by 100. The problem with your current code is that you're not converting the values to numbers and thus you're encountering what's known as string concatenation. To fix this, simply convert them to numeric values before increasing or decreasing the value:

$('input').on('keyup', function(e) {
  if (e.which === 38)
    this.value = +this.value + 99;
  else if (e.which === 40)
    this.value = +this.value - 99;
<script src=""></script>
<input type="number" />

Note that I'm using 99 instead of 100. This allows the browser's initial handling of it to also kick in. If your step value is not 1, you'll need to offset this yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download