Restrict input to letters

I use this to restrict keyboard inputs to accept only letters.

This by the way relies on jQuery.

The CSS Selector

<input type="text" class="restrict-to-letters" placeholder="Enter a number here" />

The jQuery

$('.restrict-to-letters').on('keydown',function(e){
  return isLetter(e);
});

The Javascript

function isLetter(event){
  if(event){
    var charCode = (event.which) ? event.which : event.keyCode;
    if(
        (charCode < 65 || charCode > 90) && //key code 65 to 90 is for a-z
        (charCode < 35 || charCode > 40) && //key code 35 to 40 are for navigational keys
        charCode != 8 && //key code for backspace
        charCode != 32 // key code 32 for space
      ){
      return false;
    }
  }
  return true;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s