I am trying to set keyCode on dispatched event object .
On button click, event is raised on textbox control to simulating keydown event. Event is raised successfully, but keyCode is 0. I need to send event object with correct keyCode to textbox. I've been using code from here.
How to set keyCode value in dispatched event?
<html> <head> </head> <body> <input type="button" id="btn" value="Click"></input> <input type="text" id="txt"></input> <script> document.getElementById('btn').addEventListener("click", btnClick); document.getElementById('txt').addEventListener("keydown", txtKeydown); function btnClick(e) { var txt = document.getElementById('txt'); var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) { var e = document.createEvent("KeyboardEvents"); e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1)); e.keyCode = 83; e.charCode = 0; target.dispatchEvent(e); }; var canceled = !dispatchKeyboardEvent(txt, 'keydown', true, true, // type, bubbles, cancelable window, // window 's', // key 0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick false, false, false); // Ctr, Alt, Shift } function txtKeydown(e) { console.dir(e); console.log(e.keyCode); } </script> </body> </html>
key 13 keycode is for ENTER key.
Tests of onkeydown reveal that when the "normal" enter key is pressed, keyCode=13 and location=0; when the numpad enter is pressed, keyCode=13 and location=3. So the following code can be used to set key==13 if the enter, key==176 if numpad enter: window. onkeydown=function(ev) { var e= ev || window.
I am amazed that this bug has been sitting there for ages. There seems to be a workaround using generic events. Here's a demo: http://jsbin.com/awenaq/3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With