SHREY RAJ
SHREY RAJ

Reputation: 29

How to simulate keypress events to change text content and submit a form in JavaScript?

I want to create a JavaScript function that can simulate keypress events to change the text content inside a div and then submit it using a button click event.

For example, let's say I have a div with an ID of "myDiv", and I want to change its content to "Hello world!" and then submit it using a button with an ID of "myButton". How can I achieve this using JavaScript?

I want to simulate key press events and not directly change the text content using the div.textContent method. Specifically, I want to fill and submit a form where the text input is a div element with the contenteditable attribute set to true.

Any help would be greatly appreciated. Thank you!

const tweetBox = document.querySelector("[data-testid='tweetTextarea_0']");
  tweetBox.focus();
  tweetBox.textContent = "";

  const text = "Hello, world!";
  for (const char of text) {
    const key = char.charCodeAt(0);
    console.log(key) ;
    const event = new KeyboardEvent("keypress", { keyCode: key });
    tweetBox.dispatchEvent(event);
  }

  const tweetButton = document.querySelector("[data-testid='tweetButtonInline']");
  tweetButton.click();

  console.log("\nButton Clicked");

The content inside of the div , is not being changed .

Upvotes: 1

Views: 1006

Answers (1)

JMP
JMP

Reputation: 4467

If an event is created and dispatched, then isTrusted is set to false, whereas a user-initiated event sets isTrusted to false.

This means that the default event handler for keyboard events is not fired. However, the element still receives the event, and we can add out own event handler to provide similar functionality.

onkeydown='if (!event.isTrusted) this.textContent+=event.key;'

First determine whether the action is user-initiated or not, and alter the text manually if not (if you don't check isTrusted, user-typed text doubles up).

function typeStr() {
  let str='hello world!';
  for (let ltr of str) {
    d=new KeyboardEvent("keydown", {key:ltr});
    out.dispatchEvent(d);
  }
}
<div id="out" style="border:black 2px solid" contenteditable
  onkeydown='if (!event.isTrusted) this.textContent+=event.key;'></div>
<button onclick="typeStr();">type</button>

Upvotes: 0

Related Questions