Bob Smith Bob Smith - 3 months ago 18
Javascript Question

How to populate React-generated input fields with JQuery

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).

Answer
//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)
Comments