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:
$("#mynumberinput").keydown(function(e){
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?
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:
$("#mynumberinput").keydown(function(e){
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?
Share Improve this question asked Oct 12, 2016 at 15:09 candlejackcandlejack 1,2072 gold badges24 silver badges52 bronze badges 2-
How about
<input type="number" step="100" id="mynumberinput" />
– Hackerman Commented Oct 12, 2016 at 15:12 - "But [it] didn't work" in what way did it not work? How did it go 'wrong'? Were there any error messages? What's your relevant HTML? – David Thomas Commented Oct 12, 2016 at 15:12
2 Answers
Reset to default 5Change 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="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></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.
I think the input step answer is right, but with regards to the JQuery I think you should have parseInt on just the val, and THEN subtract.
$(this).val(parseInt($(this).val()) - 100);