View Full Version : onKeyPress compatibility

05-30-2006, 08:37 PM
I've been searching on this issue for a couple hours, but nothing I've found has led me to a solution. I have the following function:

function submitEnter(buttonId, myfield, e)
var keycode;

if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
// else return true;

alert('keycode: ' + keycode);
if (keycode == 13)
alert('enter was pressed');

And the onKeyPress attribute:

onKeyPress="submitEnter('buttonId', 'fieldId');"

It works fine in IE, but not Firefox. Firefox gives the alert "keycode: undefined" for any key. Obviously, Firefox never knows when the enter key is pressed. I commented out the "else return true;" line because it was causing Firefox not to give an alert at all.

05-30-2006, 09:22 PM
One error that I see here:
onKeyPress="submitEnter('buttonId', 'fieldId');"For Netscape events model compatibility, that should be
onKeyPress="submitEnter('buttonId', 'fieldId',event);"In the Netscape events model the event is passed as the first argument to the keypress event handler. If the event is written as an HTML string in an attribute value, that string will be converted to a function like so:
function anonymous(event){
/* the event handler attribute value */
}So, you should pass that event argument on to any functions you call that need access to the event object.

That also means that you can change your function to be more browser agnostic:
function submitEnter(buttonID,myfield,e){
alert('Character or Key code: '+charinput+'\nCharacter entered: "'+String.fromCharCode(charinput)+'";);
alert('enter was pressed');
}(untested, but I think it should work as is)

Have a look at an earlier post I made about this. That should explain character input versus key codes for you.

Also, have a look at <uri:http://www.din.or.jp/~hagi3/JavaScript/JSTips/Mozilla/Samples/KeyEvent.htm> for a page where you can test the behavior of key events on various browsers.

05-30-2006, 09:40 PM
Actually, liorean, I think that problem is that JasonTC is not properly passing the event parameter.

JasonTC, try making these two changes:

onKeyPress="submitEnter(e, 'buttonId', 'fieldId');"

function submitEnter(e, buttonId, myfield)

05-30-2006, 09:42 PM
Actually, liorean, I think that problem is that JasonTC is not properly passing the event parameter.Beat you to it :p

05-30-2006, 09:49 PM
Nice. All I had to do was add that "event" argument and it works just fine. Thanks a lot.