Cross-Browser Null Key Code

In a login form, a JavaScript validation function was set to be called on key press or on login button click. However, the form wouldn’t submit in Firefox – only in IE.

Turns out that the function was checking the key code (e.which or e.keyCode) to see what key had been pressed – either 13 for the enter key, or 0 no key (i.e. the mouse click). But it turns out that Firefox records “no key” as a 1 instead of as a 0. I just changed the code to look for 13, 0, or 1, and we were set.

A better design would be to write two functions, one for key press and one for button click. The idea of checking the character code is foreign to the abstract logic of the button click procedure, so it’s really a hack to treat them as a single function. You can abstract any common code into a third function, of course.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: