Search code examples
javascriptformsmaterial-uitextfieldform-fields

Change value of Material UI input field with external javascript


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?


Solution

  • Here is what you can do:

    1. Find the Material UI input field (e.g. by class name)
    2. Look for the property named __reactPropsxxxxx (the last bits are different everytime)
    3. 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;
        }
      }
    }