Skip to content

Instantly share code, notes, and snippets.

@oze4
Created April 17, 2024 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oze4/13942c961f27ab456001a210d3905ce8 to your computer and use it in GitHub Desktop.
Save oze4/13942c961f27ab456001a210d3905ce8 to your computer and use it in GitHub Desktop.
Programmatically set input on React rendered DOM elements.
/**
* Programmatically set input.
* https://stackoverflow.com/a/72014541/10431732
*
* @param {HTMLElement} node
* @param {String} value
* @example - You would use it like this:
const textarea = document.querySelector("textarea");
const submitButton = document.querySelector('button[aria-label="Submit"]');
const TEXT_TO_TYPE = "hello, world!";
triggerInputChange(textarea, TEXT_TO_TYPE);
// Have to wait until event is complete...
// There is prob a better way to handle this...
setTimeout(() => submitButton.click(), 1500);
*/
function triggerInputChange(node, value = '') {
const inputTypes = [
window.HTMLInputElement,
window.HTMLSelectElement,
window.HTMLTextAreaElement,
];
// only process the change on elements we know have a value setter in their constructor
if (inputTypes.indexOf(node.__proto__.constructor) > -1) {
const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
const event = new Event('input', {
bubbles: true
});
setValue.call(node, value);
node.dispatchEvent(event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment