How to Prevent Special Non Alphanumeric Chars in an Input with jQuery


jQuey logo scrivi meno e fai di più

So the trick we are going to see today it’s an input where we avoid the insertion of special chars, such as esclamation marks (!), percentage (%), allowing only lettes and numbers.
The script allow the use of the arrows, backspace and delete button, preventing anything else.

Bind the keypress event on our input

The first thing to do it’s binding the keydown event on our input text. So:

  $('input[type="text"]')
	.bind('keydown',function(e) {
		// Our code here
	})

Accept only letters and numbers to be entered

Next step it’s read the pressed key, and next decide if that char it’s good for our purposes or not.
We use the e.which to read the numerical value of the input, and next we can add an if to accept only numbers and letters.
The group of keys with value between 65 and 90 are the letter of the alphabeth, between 48 and 57 are the numbers on the top of the keyboard, and from 96 and 105 are the keys in the numeric keypad.

To discriminate those letters we use a simple if.

var keypressed = e.which
if ((keypressed >=65 && keypressed <= 90) || (keypressed >=48 && keypressed <= 57) || (keypressed >= 96 && keypressed <= 105)){ // Digits and numbers are accepted // Digits and numbers are accepted // here our function } else { // The char it's not allowed. We prevent the function from going any further. e.preventDefault() return false } [/javascript]

Allow the use of arrow keys and delete and backspace

The chars we would allow the use, such as backspace and delete are numbered as 8,27,46 and between 35 and 40. In my this example I don’t accept the enter key either, but if you need it for your app the keycode it’s 13.

else if ( keypressed === 8 || keypressed === 27 || keypressed === 46 || (keypressed >= 35 && keypressed <= 40) ) { // Accepted but the event it's not propagated because those are the special chars } [/javascript] And this is the result: [html] forEach on HTML collections and arrays

[/html]

$(‘input[type=”text”]’)
.bind(‘keydown’,function(e) {
var keypressed = e.which
if(e.shiftKey && (keypressed >=48 && keypressed <= 57)) { e.preventDefault() return false } if ((keypressed >=65 && keypressed <= 90) || (keypressed >=48 && keypressed <= 57) || (keypressed >= 96 && keypressed <= 105)){ // Digits and numbers are accepted delay(function() { executeCall() },1800); } else if ( keypressed === 8 || keypressed === 27 || keypressed === 46 || (keypressed >= 35 && keypressed <= 40) ) { // Accepted but the event it's not propagated because those are the special chars } else { // We don't allow anything else e.preventDefault() return false } } }) [/javascript]

Download the example


Lascia un Commento!