3

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?

Community
  • 1
  • 1
Jules
  • 3,105
  • 2
  • 27
  • 33

2 Answers2

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

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • 1
    like your vanillajs solution, but hate your unquoted attributes. Nonetheless nice use of new attribute and shim for IE (and some other unnotable browsers;) ). – Christoph Feb 20 '12 at 16:54
4

You can use jQuery.

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