Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the keypress value from an event object in jQuery

Tags:

jquery

I want to disable users from entering a character into a HTML text input field that isnt a letter or number.

This exact functionality can be seen on the Twitter signup page (username field) https://twitter.com/signup.

Im trying to write this in jQuery. But i need to be able to grab the incomming keypress event value to test which key was pressed and if its value is acceptable.

Here's the code:

<input type="text" id="username" name="username" />

<script type="text/javascript">
$("#username").keypress(function(event){   

 // Get the keypress value
 // ...?

// If the keypress value is illegal then disable it
if (...){
   event.preventDefault();
}

});
</script>
like image 859
Jon Avatar asked May 17 '09 08:05

Jon


2 Answers

You can use the 'which' property of the event object to capture the keycode. You can use something like following code to get the corresponding character -

var c = String.fromCharCode(e.which);

See the link http://api.jquery.com/keypress/ for detailed explanation.

like image 153
Vini Avatar answered Oct 15 '22 20:10

Vini


When a user presses a key the corresponding ascii code is what is sent in the event. Use the e.which field

So your conditional could look something like this:

if ( e.which > 47 &&  e.which < 58)
{
    // it is a number
}

There are many different ways you could write the conditional. Possibly by using mapping the allowed characters into an array.

For reference, Uppercase: 65 - 90 Lowercase: 97 - 122

You should realize that this will make your app only work for people typing in English using the standard ASCII set. International users will be unable to write in your form field, because those keycodes fall outside the standard ASCII range and will be using a different encoding. Just something to consider.

Ascii Codes: http://www.petefreitag.com/cheatsheets/ascii-codes/

like image 23
Casey Avatar answered Oct 15 '22 19:10

Casey