输入输入类型编号时如何防止“0”作为第一个字符?

新手上路,请多包涵

我想防止 0 作为第一个字符。但是当我再次 focusout 和 focusin 时,然后我在第一个中添加“2”,它仍然运行,我想要不应该运行。

这是我的 HTML

 <input type="number" id="test">

我的JS

 $('#test').keypress(function(evt) {
  if (evt.which == "0".charCodeAt(0) && $(this).val().trim() == "") {
  return false;
   }
});

有人帮助或建议我该怎么做吗?谢谢你。

原文由 dedi wibisono 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 320
2 个回答

You can use input event, which also handles pasted values, String.prototype.replace() with RegExp /^0/ to replace all 0 在元素的 .value 中找到的字符

 $("#test").on("input", function() {
  if (/^0/.test(this.value)) {
    this.value = this.value.replace(/^0/, "")
  }
})
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="number" id="test">

原文由 guest271314 发布,翻译遵循 CC BY-SA 3.0 许可协议

which 属性与数字 0 的ASCII码进行比较,返回false。

 if (evt.which === 48) {
  return false;
}

检查小提琴

原文由 Sushanth – 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题