Search code examples
javascriptjquerykeypress

Detect key pressed in text input from onkeydown() inline function


I have the following

<input name='blah[]' onkeydown="itemKeyDown(this)">

Is it possible to detect what key was pressed in the itemKeyDown() function?

I tried the usual approach with:

e.keyCode || e.which

but it returns undefined.

To note: I could do it the jQuery way, but I needed to specifically attach the function call in the HTML code (inside the tags) because I'm dynamically generating a lot of copies of this text field, and this way all fields generated will inherit the function call. I don't want to have to bind a listener to a text field, all are generated.


Solution

  • Like that?

    function itemKeyDown(e) {
        console.log(e.keyCode || e.which);
    }
    <input name='blah[]' onkeydown="itemKeyDown(event)">