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.
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.
Share Improve this question edited Mar 12, 2024 at 13:06 Mark Rotteveel 110k229 gold badges156 silver badges224 bronze badges asked Apr 16, 2017 at 14:24 BrownChiLDBrownChiLD 3,74310 gold badges47 silver badges64 bronze badges2 Answers
Reset to default 4Like that?
function itemKeyDown(e) {
console.log(e.keyCode || e.which);
}
<input name='blah[]' onkeydown="itemKeyDown(event)">
<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>