javascript 在 HTML5 中显示两位数格式的输入标签(文本框控件)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32962871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:57:17  来源:igfitidea点击:

Show Input tag(textbox control) with two digit format in HTML5

javascripthtml

提问by Nimmy

How can I make an input tag, that always accepts two digits? like 01, 02, 03 etc up to 24. A leading zero should be present in case of single digits(0 to 9)

如何制作始终接受两位数的输入标签?像 01、02、03 等,最多 24 个。如果是个位数(0 到 9),则应存在前导零

<input id="hourInput" type="number" min="1" max="24" step="1"  />

回答by Salketer

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

不幸的是,在纯 HTML5 中不可能实现这一点。将需要 Javascript...

<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 to get good trafic, I'd like to add the fact that the approach I have suggested is a na?ve way to do it and will only correctly work with a min attribute higher than -9. If the number goes lower, the 0 will still get added resulting in 0-234 when the user enter a negative value of 234.

编辑:由于这个答案似乎获得了良好的流量,我想补充一个事实,即我建议的方法是一种天真的方法,并且只能正确使用高于 -9 的 min 属性。如果数字变小,当用户输入负值 234 时,0 仍然会被添加到 0-234。

回答by ?zgür Kaplan

There is no native way to do that. However you can use oninput event to format.

没有本地方法可以做到这一点。但是,您可以使用 oninput 事件进行格式化。

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

Javascript

Javascript

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

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

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

回答by ketan

You can also do using JQuery like following:

您还可以使用 JQuery,如下所示:

$(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 it helps.

希望能帮助到你。