Manipulate Hubspot Forms after loading (jquery)

Hello!

Im trying to manipulate a Hubspot Form after it loaded (change input values e.g.). I found something like this: https://community.hubspot.com/t5/APIs-Integrations/Manipulating-forms-after-loading-on-Hubspot-landing-pages/m-p/399559#M39498

So I tried some basic stuff:

 window.addEventListener('message', event => {
 if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
 $('input[name="firstname"]').val('Brian').trigger('change');
 console.log("Form loaded!");
 }
 });

There is no error, it says “form loaded!” in console and thats it.

I tried the same construct with this like its mentioned here: HubSpot Developer Documentation - HubSpot docs

hbspt.forms.create({
 portalId: 'XXXX',
 formId: 'XXXX',
 onFormSubmit: function($form) {
 $('input[name="firstname"]').val('Brian').change();
 } 
}); 

Its the same, I cant manipulate the Hubspot Form. There is an input field with a name “firstname”.

Am i doing something wrong or is their a better method to achieve what i try to do?

Regards

Michael

@mhdev

Your second codeblock using onFormSubmit rather than onFormReady.

Oh, I copied an example from the documentation.

The code i am using is this:

hbspt.forms.create({
 region: "xxx",
 portalId: "xxx",
 formId: "xxx",
 onFormReady: function($form) {
 $('input[name="firstname"]').val('Brian').change();
 }
 });

So i tested it with onFormReady and it doesnt work either for me.

Make sure your are including the script above the forms create.

Check out this pen for an example of it working

Thank your for your answer!

Your script is working like a charm, the only difference to mine (i did inlcude the js script) is that my form is embedded into an iframe and your form is not. I guess that is the problem i have.

Can you embed the form without an iframe and if so how?

Thanks in advance!

Michael

@mhdev

Ah! Yep, that would do it.

In the form options, you will see a toggle to set it to raw html. Select that and I think you will off to the races

Awesome, thank you so much for your help!

Have a great week.

Kind regards

Michael