Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate Enter In JavaScript

I try to simulate Enter in JavaScript in a specific TextArea. This is my code:

 function enter1() {
       var keyboardEvent = document.createEvent('KeyboardEvent'); 
       var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent'; 
       keyboardEvent[initMethod]('keydown', // event type : keydown, keyup, keypress
            true, // bubbles
            true, // cancelable
            window, // viewArg: should be window
            false, // ctrlKeyArg
            false, // altKeyArg
            false, // shiftKeyArg
            false, // metaKeyArg
            13, // keyCodeArg : unsigned long the virtual key code, else 0
            13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
       );
       document.getElementById('text').dispatchEvent(keyboardEvent);
 }

TextArea:

<textarea id="text"> </textarea>

When I call enter1(), it doesn't do anything in the TextArea. Why is this?

like image 733
Luca Laiton Avatar asked May 02 '15 14:05

Luca Laiton


People also ask

How to simulate a click with JavaScript?

- GeeksforGeeks How to simulate a click with JavaScript ? Method 1: Using the click () method: The click () method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

Is it possible to simulate pressing [Enter] key on input text?

javascript - Simulate pressing [enter] key on input text - Stack Overflow My code worked perfectly on changed the value of input automatic on page load with a delay between it. But there's another problem, When I tried to simulate pressing the [enter] key on the input,...

How to simulate a keypress event in JavaScript?

How to simulate a keypress event in JavaScript? To simulate a key press event, use event handlers. You can try to run the following code to simulate a key press event

How to trigger a button with JavaScript?

Trigger a button click on keyboard "enter" with JavaScript. Trigger a Button Click on Enter Press the "Enter" key inside the input field to trigger the button:


1 Answers

For anyone that has a problem dispatching the event, try adding the key-value pair bubbles: true:

const keyboardEvent = new KeyboardEvent('keydown', {
    code: 'Enter',
    key: 'Enter',
    charCode: 13,
    keyCode: 13,
    view: window,
    bubbles: true
});
like image 78
mliakos Avatar answered Sep 28 '22 04:09

mliakos