Say I am visiting an online form that uses Material UI, like this https://codesandbox.io/s/material-demo-forked-kigre?file=/index.js
I want to populate the input field with some value using console javascript, e.g.
for (input of document.getElementsByTagName('input')) {
input.value = "new value";
console.log(input.value);
}
This first appears to work as the input field value does change and the console can log the updated value. However, as you can see the display of the actual value "Your input value is: test" doesn't change, and once you click on the input field, it reverts back to its original value.
Can you write up an external javascript that can actually change the input field value? I believe it is not that simple, may be something like dispatching events is required?
CodePudding user response:
Here is what you can do:
- Find the Material UI input field (e.g. by class name)
- Look for the property named
__reactPropsxxxxx
(the last bits are different everytime) - Execute the
onChange
function
This is an example code:
for (input of document.getElementsByClassName("MuiInput-input")) {
for (key in input) {
if (key.startsWith("__reactProps")) {
input[key].onChange({target: {value: "changed!"}});
break;
}
}
}