Show input tag (text box control) with two-digit format in HTML5

How can I create an input tag that always takes two digits? e.g. 01, 02, 03, etc. up to 24. The leading zero must be present in the case of single digits (from 0 to 9)

<input id="hourInput" type="number" min="1" max="24" step="1" /> 
+7
source share
3 answers

Unfortunately, this is not possible in pure HTML5 to achieve this. Javascript will be required ...

 <input id="hourInput" type="number" min="1" max="24" step="1" onchange="if(parseInt(this.value,10)<10)this.value='0'+this.value;" /> 

EDIT: Since this answer seems like a good trafic, I would like to add the fact that the approach I proposed is a naive way to do this and will only work correctly with the min attribute above -9. If the number falls below, then the value 0 will be added as a result of 0-234 when the user enters a negative value of 234.

+17
source

There is no own way to do this. However, you can use the oninput event for formatting.

  <input id="hourInput" type="number" oninput='format(this)' min="1" max="24" step="1" /> 

Javascript

 function format(input){ if(input.value.length === 1){ input.value = "0" + input.value; } } 

http://jsbin.com/dedixapasi/edit?html,js,output

+7
source

You can also use jQuery as shown below:

 $(document).ready(function() { $("#hourInput").keydown(function(event) { if ( event.keyCode == 46 || event.keyCode == 8 ) { } else { if (event.keyCode < 48 || event.keyCode > 57 ) { event.preventDefault(); } } }); $("#hourInput").keyup(function(event) { var str = $('#hourInput').val(); if(str > 24) { $('#hourInput').val(str.substring(0,str.length - 1)); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input id="hourInput" type="number" min="1" step="1" /> 

Hope this helps.

0
source

All Articles