The problem:
- Limit allowed characters in a HTML input to a-z A-Z only.
- For business requirements this needs to be done on KeyPress so that the character simply isnt allowed to even appear in the input.
- Tab, enter, arrows, backspace, shift are all allowed. The user must be able to freely move in and out of the textbox, delete characters etc etc.
This is the starting point of my code…
var keyCode = (e.keyCode ? e.keyCode : e.which);
However every value that I get in keyCode doesnt correspond to any of the character charts I have seen on the web. For example the character “h” gives me a return code of 104.
Is KeyCode different to CharCode? Which code contains the control characters? Do I need to convert?
How can I restrict the input to a-z A-Z and allow the keys I need in JavaScript?
The answers to all your questions can be found on the following page.
…but in summary:
keypressevent.keypressevent, all browsers except IE <= 8 store the character code in the event’swhichproperty. Most but not all of these browsers also store the character code in thecharCodeproperty.keypressevent, IE <= 8 stores the character code in thekeyCodeproperty.This means to get the character code corresponding to the keypress, the following will work everywhere, assuming a keypress event object is stored in a variable called
e:This will generally return you a character code where one exists and 0 otherwise. There are a few cases where you’ll get a non-zero value when you shouldn’t:
The workaround for the first problem is a little involved and requires using the
keydownevent as well.