Created
April 17, 2024 04:56
-
-
Save matthewoestreich/13942c961f27ab456001a210d3905ce8 to your computer and use it in GitHub Desktop.
Programmatically set input on React rendered DOM elements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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