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 );
I was trying to dispatch a keyPress event inside an Input element to pass the data-bind condition(KnockOut js) event , but unfortunately KeyPress didn't worked for me, Instead I used change event in place of it.
so I did this:
element = document.getElementById('idTxtBx_SAOTCS_ProofConfirmation');
element.value = '8885'; // this alone was not working as keypress.
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true); // adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);
so .value and change event together made, fake inputText or keypressed event successful.
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