Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Leading Zeros On Input Number Fields

I have two input fields representing hours and minutes.

<input type="number" min="0" max="24" step="1" value="00" class="hours">
<input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes">

Which display as:

0:0

Or:

5:3

Is there a way to display it as:

00:00

Or:

05:03

i.e in 24-hour data format (before people suggest it, I can't use type="time").

like image 487
Oam Psy Avatar asked Apr 01 '16 14:04

Oam Psy


2 Answers

You can add an onchange attribute to your input tag, which calls a javascript function.

    <script>
       function MyFunction() {
           var minuteValue = document.getElementById("minutes").value;
           if (minuteValue.length < 2) {
               minuteValue = "0" + minuteValue;
           }
           alert(minuteValue);
       }
    </script>

    <input id="minutes" onchange="MyFunction()"/>
like image 197
fix Avatar answered Sep 19 '22 21:09

fix


 function formatNums(num){
   if (nums < 10){
     return "0" + num;
   }
 }

 var formattedHours = formatNums(hours);
 var formattedMinutes = formatNums(minutes);

NOTE: This method uses type="text" so be sure to convert back to a number if needed. Number(formattedHours);

like image 35
Matt Butler Avatar answered Sep 19 '22 21:09

Matt Butler