Skip to content

Instantly share code, notes, and snippets.

@dossy
Last active November 27, 2023 23:32
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 dossy/d02d4d722f714c3a4519a03e690432bc to your computer and use it in GitHub Desktop.
Save dossy/d02d4d722f714c3a4519a03e690432bc to your computer and use it in GitHub Desktop.
dispatchEvent on input/textarea ignored
// from: https://github.com/facebook/react/issues/10135#issuecomment-314441175
// fatfisz <https://github.com/fatfisz> commented on Jul 11, 2017
// Just leaving a solution for future reference (checked in Edge 15, IE 11, FF 53, Chrome 59):
function setNativeValue(element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
// Use it like so:
setNativeValue(textarea, 'some text');
textarea.dispatchEvent(new Event('input', { bubbles: true }));
// Object.getOwnPropertyDescriptor(element, ...) returns undefined from a
// Chrome extension context, so use this instead:
function setNativeValue(element, value) {
const elementValue = Object.getOwnPropertyDescriptor(element, 'value');
const valueSetter = elementValue && elementValue.set;
const prototype = Object.getPrototypeOf(element);
const prototypeValue = Object.getOwnPropertyDescriptor(prototype, 'value');
const prototypeValueSetter = prototypeValue && prototypeValue.set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment