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>
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With