'Making the step act as a guide in <input type="number">
How could I make the step attribute for an <input type="number"> act more of a guide, so I could input any positive integer but the increment arrows would change the current value by a fixed amount?
e.g. I could enter 0,1,2,3,4,5,6,7,... and the step would increment the values as 0,6,12,18,24,... etc...
I could implement this if I knew how to capture the step up/step down events in JavaScript. However, I can't find a way to do that. I've shown exactly what I'd like in the pseudo code below:
<input id="num" type="number">
<script>
inp = document.getElementById("num");
var increment = 6;
if ( step up pressed ){
inp.value += increment;
}
else if (step down pressed ){
inp.value -= increment;
}
</script>
Solution 1:[1]
Would this work?
<input id="num" type="number" step="6">
Solution 2:[2]
It seems like a horrible hack but here's an answer to my question:
<input id='num' type=number step=0.00001 onchange="increment()">
<script>
document.prev_num = document.getElementById("num").value;
function increment() {
var step = 6;
var catch_step = 0.00001;
var curr_num = parseFloat(document.getElementById("num").value);
if ( Math.abs(curr_num - (document.prev_num + catch_step)) < 1e-7 ){
curr_num = curr_num - catch_step + step;
}
else if (Math.abs(curr_num - (document.prev_num - catch_step)) < 1e-7){
curr_num = curr_num + catch_step - step;
}
else if (curr_num != parseInt(curr_num)){
alert("You can only input integers.")
curr_num = parseInt(curr_num);
}
document.getElementById("num").value = curr_num;
document.prev_num = curr_num;
}
</script>
So HTML forces the numbers to be multiples of 0.00001, which includes all integers.
Javascript then acts when the number is changed. If that change is only a change of 0.000001 the step button was almost certainly pressed.
Non integers won't be accepted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | patstuart |
| Solution 2 | Matt Ellis |
