How can I prevent letters inside a text element?

2019-03-02 13:51发布

问题:

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.