Domanda

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

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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.

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.

Adding on to some of the other answers that suggest using an event listener. I've tested this with jquery in chrome and it seems to work well with the padding without the slight flashing side effect.

<input type="number" id="input-element-id" value="00">

<script>
    $('#input-element-id').on('input', function() { 
        const value = $(this).prop('value')
        $(this).prop('value', value.padStart(2, '0')) 
    })
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top