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

Nim*_*mmy 7 html javascript html5

如何创建一个始终接受两位数的输入标签?如01,02,03等,最多24个.如果是单个数字(0到9),则应该存在前导零

<input id="hourInput" type="number" min="1" max="24" step="1"  />
Run Code Online (Sandbox Code Playgroud)

Sal*_*ter 18

不幸的是,在纯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;" />
Run Code Online (Sandbox Code Playgroud)

编辑:由于这个答案似乎得到了很好的交流,我想补充一点,我所建议的方法是一种天真的方式,并且只能正确地使用高于-9的min属性.如果数字变低,当用户输入负值234时,0仍然会被添加,从而导致0-234.

  • 也可以:<input id ="hourInput"type ="number"min ="1"max ="24"step ="1"onchange ="if(this.value.length == 1)this.value =' 0' + THIS.VALUE;" /> (2认同)

Özg*_*lan 8

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

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

使用Javascript

function format(input){
  if(input.value.length === 1){
    input.value = "0" + input.value;
  }
}
Run Code Online (Sandbox Code Playgroud)

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