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("bob@example.com").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).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bob Smith
  • 133
  • 8
  • It really depends on how these fields are implemented. It sounds like these are [Controlled Components](https://facebook.github.io/react/docs/forms.html#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. – Michael Parker Jun 28 '16 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. – Michael Parker Jun 28 '16 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 http://stackoverflow.com/a/2856602/6524176, but I've not had any luck. – Bob Smith Jun 28 '16 at 16:15
  • Check out my answer – Michael Parker Jun 28 '16 at 16:27

2 Answers2

5
//find element
let elem = document.querySelector("#emailAddress");
//create event
let event = new Event('input', { bubbles: true });
//set value
elem.value="bob@example.com";
//trigger event
elem.dispatchEvent(event)
Kokovin Vladislav
  • 10,241
  • 5
  • 38
  • 36
  • 1
    You deserve a kiss, I was looking for this solution for 3 months and I had given up. THANK YOU!!!!!!!!!!!!!!!!!!!!! – Samul Sep 20 '16 at 16:15
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);
Michael Parker
  • 12,724
  • 5
  • 37
  • 58
  • Thanks. My element didn't have an `onchange` member, unfortunately, but the solution from @Utro's answer worked a treat. – Bob Smith Jun 29 '16 at 11:52