CMS Development

MJohnston2
Member

Pre-populating form fields with react

SOLVE

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

1 Accepted solution
tjoyce
Solution
Recognized Expert | Elite Partner
Recognized Expert | Elite Partner

Pre-populating form fields with react

SOLVE

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

View solution in original post

4 Replies 4
tjoyce
Solution
Recognized Expert | Elite Partner
Recognized Expert | Elite Partner

Pre-populating form fields with react

SOLVE

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

MSoftware
Member

Pre-populating form fields with react

SOLVE

@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?

ishields2
Participant

Pre-populating form fields with react

SOLVE

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').contentDocument
formDocument.getElementById('email-' + event.data.id).value = 'example@email.com';
}
});
0 Upvotes
dennisedson
HubSpot Product Team
HubSpot Product Team

Pre-populating form fields with react

SOLVE

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?

0 Upvotes