views:

3623

answers:

4

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?

A: 

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.

Greg
+3  A: 

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;
}
+3  A: 

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(holder){
     if(key == /*desired code*/){
            /*execute stuff*/
     }
}

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

mike nvck
+1  A: 

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.

antonioh