Force leading zero in number input

怎甘沉沦 提交于 2019-11-30 18:45:26

I'm afraid there is not native HTML way to do that unless using a Select tag. If you are using a text input you have to add the leading 0 on the 10 first values by javascript.

I use this to just prepend zeros as needed:

<script>
  function leadingZeros(input) {
    if(!isNaN(input.value) && input.value.length === 1) {
      input.value = '0' + input.value;
    }
  }
</script>

And I just call that on the input's various events how ever works best for me, for instance:

<input type="number"
       value="00"
       onchange="leadingZeros(this)"
       onkeyup="leadingZeros(this)"
       onclick="leadingZeros(this)" />

It's not an ideal solution, mainly because there's a slight visual change as the user changes the number and the zero is prepended, but it works for me :)

Edit: Forgot to mention, I appreciate the answer asked for a native solution without javascript, but I wanted to provide something for people landing here through a Google search.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!