How could I make the step attribute for a <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.
eg 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>
这行得通吗?
<input id="num" type="number" step="6">
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.