Restrict keyboard character input with jQuery

The user gets frustrated when its fill all information in the form and submits it then the data not being submitted because of invalid input.

In this case, instead of checking all values on your server side script you can also do this in Client side with jQuery JavaScript.

Now the user only able to input valid character from its keyboard.

For example, you has doesn’t require alphabets in age field then you can restrict the input element to take only numbers.

In this tutorial, I show how you restrict keyboard character with jQuery.
keyboard character

 


Contents

  1. Example
  2. Demo
  3. Conclusion

 

1. Example

For validating input, you can use pressed key ASCII code and check it.

If you don’t know the ASCII code of a character then you can view it from here and define your condition in keypress Event handler.

Allowing only number characters

You can use the event.which to get ASCII code of pressed character to check.

Below script allows only number input.

$(document).ready(function(){
  $("#age").keypress(function(e){
     var keyCode = e.which;
    /*
      8 - (backspace)
      32 - (space)
      48-57 - (0-9)Numbers
    */
 
    if ( (keyCode != 8 || keyCode ==32 ) && (keyCode < 48 || keyCode > 57)) { 
      return false;
    }
  });
});

Not allowing special characters

You can either return false or call preventDefault() method on event variable.

$("#name").keypress(function(e){
 var keyCode = e.which;
 
 /* 
 48-57 - (0-9)Numbers
 65-90 - (A-Z)
 97-122 - (a-z)
 8 - (backspace)
 32 - (space)
 */
 // Not allow special 
 if ( !( (keyCode >= 48 && keyCode <= 57) 
   ||(keyCode >= 65 && keyCode <= 90) 
   || (keyCode >= 97 && keyCode <= 122) ) 
   && keyCode != 8 && keyCode != 32) {
   e.preventDefault();
 }
});

 

2. Demo

The first input box does not take a special character and the second only take numbers.


 

3. Conclusion

You can also use it to restrict some of the characters or perform an action based on the character pressed e.g. when enter key pressed you can submit your form.

Spread the love

Related Post

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *