I need to trigger or say dispatchEvent KeyPress inside an Input box, I have tried a lot with "initKeyboardEvent" , "initKeyEvent" , "createEvent", even I found similar question's answers but nothing seems to work, neither in firefox, nor in chrome (I think they may be deprecated), as KeyboardEvent.initKeyEvent(), is deprecated.
like we have
document.getElemntByID('button').click();
I want to do something like:
document.getElemntById('email').keyPress(charCode('a'));
but unfortunately I am not able to make keypress work in any way.
I know it is possible in jQuery , but I want to do it in pure javascript, after all jquery uses Javascript in backend , so there must be a way , if I am not wrong.
====Update=========
I wonder
window.addEventListener('keydown', keyDown(), true);
function keyDown(){
alert('keydown');
}
var fireOnThis = document.getElementById('pwph');
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keydown', true, true, window, false, false, false, false, 72, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keydown', true, true, window, 1 );
evObj.keyCode = 72;
}
fireOnThis.dispatchEvent(evObj);
This code returns me true , and even the eventListner is catching this event, then why am I not able to see any text inside the input box?
====================update============================
This seems to work for everyone, but why does it leaves my text field empty, even after returning true?
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
charCode('a')
will invoke the function... You need to pass function expression... – Quaggyonkeydown
event to the DOM Element? Like:<input type="text" onkeydown="function()">
– Stoup