I am trying to pre-populate some of the input fields in our form which is integrated with our react application.
I came across this thread which uses jQuery:
https://community.hubspot.com/t5/CMS-Development/Embedded-Form-Populating-form-fields/td-p/284953
I also read through the hubspot docs which only shows jQuery options for editing input fields:
https://legacydocs.hubspot.com/docs/methods/forms/advanced_form_options
I tried multiple solutions on there and unfortunately jQuery doesn’t play well with React. I even tried using this NPM package and tried editing via the onReady function as well as in the componentDidMount lifecycle method:
https://www.npmjs.com/package/react-hubspot-form
Any idea how to auto-populate form fields with vanilla Javascript, or in a way that works with react?
Thanks in advance,
Michael
Hey @MJohnston2
Good question! Adding a couple people to this who might be able to help.
@tjoyce , @kierana! Do either of you have a solution for this?
Hi @MJohnston2 -
You can use the global javascript events to populate form fields
window.addEventListener("message", function(event){
if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
var form = document.getElementById('form[data-form-id="' + event.data.id + '"]');
form.querySelector('.company_name')[0].value = 'Google';
}
});
Something like that
@tjoyce I’m wondering how you’re accessing the HubSpot form like this as the HubSpot form I’m trying to reach is in an iframe?
Because it’s in an iframe I had to do this
window.addEventListener("message", function(event){ if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') { var formDocument = document.getElementById('hs-form-iframe-0').contentDocumentformDocument.getElementById('email-' + event.data.id).value = 'example@email.com'; }});