How can I prevent letters inside a text element?

痴心易碎 提交于 2019-12-01 23:28:46

You can use jQuery.

$("#myField").keyup(function() {
    $("#myField").val(this.value.match(/[0-9]*/));
});
<script>
function checkPattern(elem) {
  if(!elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
    alert('The value must be 3 digits.');
  }
}   
</script>
<input maxlength=3 pattern=[0-9]{3} onchange=
   checkPattern(this)>

Modify the error handling according to the application. The idea is to use an HTML5 pattern attribute and back it up with simple JavaScript code, for browsers that do not support the attribute but have JavaScript disabled.

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