最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display Leading Zeros On Input Number Fields - Stack Overflow

programmeradmin6浏览0评论

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">

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

Share Improve this question edited Apr 1, 2016 at 15:10 sabithpocker 15.6k1 gold badge43 silver badges77 bronze badges asked Apr 1, 2016 at 14:57 Oam PsyOam Psy 8,66135 gold badges96 silver badges166 bronze badges 3
  • Check out this thread stackoverflow.com/questions/14638018/…. It's not exactly what you're doing but the JavaScript formatting for hours and minutes should work. – Andy B Commented Apr 1, 2016 at 15:03
  • 1 duplicated? stackoverflow.com/questions/20684737/… – Javier Conde Commented Apr 1, 2016 at 15:04
  • Actually this: stackoverflow.com/questions/6312993/… – Andy B Commented Apr 1, 2016 at 15:06
Add a comment  | 

4 Answers 4

Reset to default 9

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()"/>
 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);

Add a leading zero with a JavaScript function.

const hours = document.getElementById("hours");
const minutes = document.getElementById("minutes");

function addLeadingZero(value) {
  return value.length < 2 ? "0" + value : value;
}

hours.addEventListener("input", function() {
  hours.value = addLeadingZero(hours.value);
});

minutes.addEventListener("input", function() {
  minutes.value = addLeadingZero(minutes.value);
});
<input type="number" min="0" max="24" value="00" id="hours" class="hours">
<input type="number" min="0" max="59" value="00" id="minutes" class="minutes">

simple is the best

`${number}`.padStart(2, '0')
发布评论

评论列表(0)

  1. 暂无评论