问题
I'm writing an alarm web app. I have two number inputs, one for the hours, one for the minutes. Thus, when I use my keyboard arrows, they go from 0 to 23/59. Is there an HTML native way to make them go from 00 (01,02, et.) to 23/59 instead ?
I'm only worried about the UI aspects as my JS manages the missing 0 anyway.
EDIT - As requested :
What I have :

What I want :

Instead of going from 0,1,2 to 59, I'd like to automatically have a leading 0 when the number is smaller than 10 (00,01,02 to 59).
回答1:
I'm afraid there is not native HTML way to do that unless using a Select tag. If you are using a text input you have to add the leading 0 on the 10 first values by javascript.
回答2:
I use this to just prepend zeros as needed:
<script>
function leadingZeros(input) {
if(!isNaN(input.value) && input.value.length === 1) {
input.value = '0' + input.value;
}
}
</script>
And I just call that on the input's various events how ever works best for me, for instance:
<input type="number"
value="00"
onchange="leadingZeros(this)"
onkeyup="leadingZeros(this)"
onclick="leadingZeros(this)" />
It's not an ideal solution, mainly because there's a slight visual change as the user changes the number and the zero is prepended, but it works for me :)
Edit: Forgot to mention, I appreciate the answer asked for a native solution without javascript, but I wanted to provide something for people landing here through a Google search.
来源:https://stackoverflow.com/questions/20684737/force-leading-zero-in-number-input