Allow text box only for letters using jQuery?

Accepted answer

The accepted answer may be short, but it is seriously flawed (see this fiddle):

  • The cursor moves to the end, no matter what key is pressed.
  • Non-letters are displayed momentarily, then disappear.
  • It is problematic on Chrome for Android (see my comment).

A better way

The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):

$(".alpha-only").on("keydown", function(event){
  // Allow controls such as backspace, tab etc.
  var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];

  // Allow letters
  for(var i = 65; i <= 90; i++){
    arr.push(i);
  }

  // Prevent default if not in array
  if(jQuery.inArray(event.which, arr) === -1){
    event.preventDefault();
  }
});

Note that this allows upper-case and lower-case letters.

I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.

Modify on paste only

Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:

$(".alpha-only").on("input", function(){
  var regexp = /[^a-zA-Z]/g;
  if($(this).val().match(regexp)){
    $(this).val( $(this).val().replace(regexp,'') );
  }
});

This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.

Avoiding autocorrect

Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.

To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.


<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">

And can be the same to onblur for evil user who like to paste instead of typing ;)

[+] Pretty jQuery code:

<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>