2

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.

2 Answers 2

4

Like that?

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

Sign up to request clarification or add additional context in comments.

1 Comment

crap, ok now i know why it didnt work. i used "this" in the argument instead of event geesh, thanks man.got it working using itemKeyDown(this,event)
3

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

this keyword doesn't carry any information about the event onkeydown it represent the DOM element (input)

to get the event data you should pass event keyword like:

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

<script>
function itemKeyDown(e)
{
  console.log(e.keyCode)
}

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.