Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force leading zero in number input

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 :

Current

What I want :

Objective

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).

like image 452
Simon Avatar asked Dec 19 '13 14:12

Simon


3 Answers

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.

like image 128
apbarratt Avatar answered Oct 05 '22 07:10

apbarratt


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.

like image 31
Guillaume Raymond Avatar answered Oct 05 '22 07:10

Guillaume Raymond


The correct, modern solution to OP's problem would be to use a input with type=time and then they don't have to worry about leading zeros or any of this other stuffs.

like image 1
Rossman Avatar answered Oct 05 '22 05:10

Rossman