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?
- 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.
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? To simulate a key press event, use event handlers. You can try to run the following code to simulate a key press event
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:
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
});
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