javascript dispatchEvent Keypress, returns true , but input field is still empty
Asked Answered
P

3

7

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 );
Pubescent answered 25/4, 2016 at 13:27 Comment(8)
charCode('a') will invoke the function... You need to pass function expression...Quaggy
How about adding the onkeydown event to the DOM Element? Like: <input type="text" onkeydown="function()">Stoup
Possible duplicate of Invoking KeyPress Event Without Actually Pressing KeyCatena
Input element is not my hand :)Pubescent
@Boratzan yea may be but that code does not work for me, I wonder why..returns me true but nothing happens to the input field ,it is still emptyPubescent
9 is the keyCode for tabulation, right?Nicobarese
yea right, this is just an example, 72 which is a keycode for "h" does not work either, also if there is some text already in the input field , backspace keycode 8 also does not work. in whole no keyboard event firing on input field.Pubescent
you can check the same code above with any website which have an input field, just change the id, on which you'll dispatch the event.Pubescent
P
5

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.

Pubescent answered 27/4, 2016 at 8:39 Comment(0)
T
0

i think so like you want to add event listener on input box

           var element = document.getElementById("email");

            document.getElementById("email").addEventListener("keypress", function() {
                console.log("keypresh")

            })
            var evt = document.createEvent("KeyboardEvent");
            evt.initEvent("keypress", false, true);
            // adding this created a magic and passes it as if keypressed
            element.dispatchEvent(evt);
Terceira answered 25/4, 2016 at 17:19 Comment(2)
addEventListner is something which Listens when an event is fired,I don't want to Listen , I want to Fire or dispatch an event (keypress), on an Input field.Pubescent
I have gone through this Link already, Mouse events works but not keyboard events: var keyEvent = new KeyboardEvent("keydown", {key : "a", char : "a", shiftKey: true}); document.getElementById('email').dispatchEvent(keyEvent); returns true , but does not enter any character in the input box whose ID is given.Pubescent
I
0

initEvent is deprecated or about to be removed. Instead, you can use it like this:

element = document.getElementById('idTxtBx_SAOTCS_ProofConfirmation');
element.value = '8885';   // this alone was not working as keypress.

const evt = new Event("change", {
    bubbles: false,
    cancelable: true
});

element.dispatchEvent(evt);
Interlay answered 4/9, 2023 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.