How can I prevent letters inside a text element?

前提是你 提交于 2019-12-20 02:37:53

问题


I like to have an input with maximum length 3.

These input value should be only numbers no letters.

By referring to this post: why is <input type="number" maxlength="3"> not working in Safari? you can see that I can't use <input type="numbers">

So how can I prevent letters inside an text-input-element?


回答1:


You can use jQuery.

$("#myField").keyup(function() {
    $("#myField").val(this.value.match(/[0-9]*/));
});



回答2:


<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.



来源:https://stackoverflow.com/questions/9363661/how-can-i-prevent-letters-inside-a-text-element

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