Skip to content Skip to sidebar Skip to footer

How Can I Prevent Letters Inside A Text Element?

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 not

Solution 1:

<script>functioncheckPattern(elem) {
  if(!elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
    alert('The value must be 3 digits.');
  }
}   
</script><inputmaxlength=3pattern=[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.

Solution 2:

You can use jQuery.

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

Post a Comment for "How Can I Prevent Letters Inside A Text Element?"