2

I'm trying to write a bookmarklet to autofill a form, to simplify manual testing. The site is implemented in React. I've tried using JQuery, for example:

$("#emailAddress").val("[email protected]").changed()

While the input field is visibly updated in the browser, it appears that under the hood the field is not recognised as changed, as validation fails on form submit, saying the data is missing.

Is there a workable way to autopopulate the React form fields using ad-hoc JS, without changing any of the source code?

(Note: I understand that this sort of direct manipulation is not the correct way to work with React in general app development. Here, I'm looking for any solution, no matter how hacky, to simplify ad-hoc manual testing).

4
  • It really depends on how these fields are implemented. It sounds like these are Controlled Components, which means that React is controlling what value each input is supposed to have. A popular design pattern that's being used with React-based websites is to attach an onChange handler to each input field, where each change event will send the new value of the field to some centralized store, which will cause the React component to re-render with the new value present. Commented Jun 28, 2016 at 15:43
  • ...so I think you'd want to manually fire a change event on each field that contains some value, which will cause this centralized store to update each field with the values you want. Commented Jun 28, 2016 at 15:44
  • @MichaelParker -- thanks, yeah, the site is using the onChange mechanism as you describe. Any ideas on how to generate an appropriate change event? I've tried as per stackoverflow.com/a/2856602/6524176, but I've not had any luck. Commented Jun 28, 2016 at 16:15
  • Check out my answer Commented Jun 28, 2016 at 16:27

2 Answers 2

5
//find element
let elem = document.querySelector("#emailAddress");
//create event
let event = new Event('input', { bubbles: true });
//set value
elem.value="[email protected]";
//trigger event
elem.dispatchEvent(event)
Sign up to request clarification or add additional context in comments.

1 Comment

You deserve a kiss, I was looking for this solution for 3 months and I had given up. THANK YOU!!!!!!!!!!!!!!!!!!!!!
0

From our discussion in the comments, my guess is that you'll want to fire a change event for each input you plan on modifying.

var element = document.getElementById('emailAddress'),
    event = {
        target: {
            value: 'new value for the input'
        }
    };
element.onchange(event);

1 Comment

Thanks. My element didn't have an onchange member, unfortunately, but the solution from @Utro's answer worked a treat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.