9
votes

From an input text I need to call a function to capture the onkeydown event and I need to pass a parameter to that event, for example:

<input type="text" onkeydown="TextOnKeyDown('myPrefix');" />...

Then in that function I need to know what key was pressed. I use

function TextOnKeyDown(prefix) {
    var key = event.keyCode; 
    ...
}

This works like a charm in IE, but not in Firefox. I've read that for firefox you have to pass an argument to the handler and then use it to get the key, something similar to:

<input type="text" onkeydown="detectKey(event)"/>
...
function detectKey(e){
     var key = (document.all) ? e.keyCode : e.which; 
     ...    
} 

But I cannot get to pass my parameter and the needed event parameter for firefox. Any suggestions?

5

5 Answers

9
votes

I wrote this yesterday, works in both FF and IE =>

//execute this during initialization
document.onkeydown = function(event) {
    var holder;
    //IE uses this
    if(window.event) {
        holder = window.event.keyCode;
    }
    //FF uses this
    else {
        holder = event.which;
    } 
    keyz(holder);
}

function keyz(key) {
    if(key === /*desired code*/) {
        /*execute stuff*/
    }
}

you will want to replace document.onkeydown with [your input].onkeydown

7
votes

I use this in firefox and it works:

<input .... onkeypress="return isNumberKey(event);">

and then the js funcion:

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if(charCode==37||charCode==39||charCode==46)return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;

    return true;
}
7
votes

None of the proposed solutions worked as what I needed was to add my own parameter apart from the necessary "event" parameter for Firefox to get the keyCode. Anyway the helped, thanks guys. I put the final solution for future readers:

In the end I just had to add the "event" parameter to the caller:

<input type="text" onkeydown="TextOnKeyDown('myPrefix', event);" />

and the handler:

function TextOnKeyDown(prefix, evt) {    
   var key = (evt.which) ? evt.which : evt.keyCode;
...
}

Somehow it didn't work before, I don't know why.

1
votes

One more twist here that combines getting the event and the keyCode:

function calledOnKeypress(winEvent) {
    var keyCode;
    // event passed as param in Firefox, not IE where it's defined as window.event
    if(!winEvent) {
        winEvent = window.event;
        keyCode = winEvent.keyCode;
    }
    else { // ff
        keyCode = winEvent.which;
    }
}
0
votes

You can use arguments[0]:

<input type="text" onkeydown="detectKey(arguments[0])"/>

To get the IE event in there too you could do:

<input type="text" onkeydown="detectKey(arguments[0] ? arguments[0] : event)"/>

Or change your detectKey(e) function to check if e is set and use event if it's not.