Lead Capture Tools

dash-flow-io
Member

New Forms: How to fill hidden fields with JavaScript

SOLVE

Huge pain point:

The Legacy Forms allowed to inject javascript to for example update form values or write data to hidden fields for tracking or various other use cases.

 

 

 

 

 <script>
   hbspt.forms.create({
     css: '',
     portalId: '{{portalId}}',
     formId: '{{formId}}',
     onFormReady: function($form) {
            $('input[name="stringtest"]').val("kitkat2").change();
     }
   });
 </script>

 

 

 

 


The new forms use a pure iframe implementation.

 

 

 

 

<script src="https://js-eu1.hsforms.net/forms/embed/12345.js" defer></script>
<div class="hs-form-frame" data-region="eu1" data-form-id="{{id}}" data-portal-id="{{portal}}"></div>

 

 

How can this be done with the new forms?

 

With global form events - set field value one could set hidden fields, but it is unclear how to tell the iframe to execute this javascript.

0 Upvotes
1 Accepted solution
TomM2
Solution
Thought Leader | Platinum Partner
Thought Leader | Platinum Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hey @dash-flow-io  I can't definitely see this being a large pain point. I'd recomend sharing this with the product team through a feature request on the ideas forum here

Tom Mahon
Technical Consultant | Solutions Engineer | Community Champion
Baskey Digitial

Book a consultation

Did my post help answer your query? Help the community (and me) by marking it as a solution.


View solution in original post

0 Upvotes
9 Replies 9
Mike_Eastwood
Recognized Expert | Gold Partner
Recognized Expert | Gold Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hi @dash-flow-io 

 

p.s. My script is embedded in the html of a custom module; but I've also made it work in the javascript using the onFormReady Embed Code Callback.

 

IMPORTANT: The form must be "Set as raw HTML form" in the Form's Style Options (so, this only works for Markeitng Pro or Enterprise).

 

Have fun

Mike

 

Here to learn more about HubSpot and share my HubSpot Knowledge. I'm the founder of Webalite a Gold HubSpot Partner Agency based in Wellington, New Zealand and the founder of Portal-iQ the world's first automated HubSpot Portal Audit that helps you work smarter with HubSpot.

0 Upvotes
Mike_Eastwood
Recognized Expert | Gold Partner
Recognized Expert | Gold Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hi @dash-flow-io 

 

It works! I changed the javascript and removed the iFrame targeting.

 

Before (using old iFrame implementation)

...
    document.getElementById("hs-form-iframe-0").contentDocument.querySelector('input[name="change_me"]').value = change_me;
...

After

...
    document.querySelector('input[name="change_me"]').value = change_me;
...

 

Final Code

<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js" defer></script>
<script>
var change_me   = "123";
  
window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
    document.querySelector('input[name="change_me"]').value = change_me;
  }
});
</script>

 

Does it work for you?

Mike

 

Here to learn more about HubSpot and share my HubSpot Knowledge. I'm the founder of Webalite a Gold HubSpot Partner Agency based in Wellington, New Zealand and the founder of Portal-iQ the world's first automated HubSpot Portal Audit that helps you work smarter with HubSpot.

0 Upvotes
dash-flow-io
Member

New Forms: How to fill hidden fields with JavaScript

SOLVE

Your example refers to the legacy forms, not the new multi-step forms.

 

0 Upvotes
dash-flow-io
Member

New Forms: How to fill hidden fields with JavaScript

SOLVE
The following approaches also fail:

1.
 FAIL: prefill values in the iframe div

 

 

<div class="hs-form-frame">
data-region="eu1"
data-form-id="{{formid}}"
data-portal-id="{{portal}}"
data-hs-custom-field-myfield="example"
data-hs-prefill="myfield=example"
</div>

 

 

 

 

2. FAILsending postMessage to iframe

 

 

<html>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const FORM_ID = '...';
    const FIELD_NAME = 'myfield'; // Updated field name
    const IFRAME_SELECTOR = `iframe[data-test-id="embedded-form-${FORM_ID}"]`;

    const handleFormReady = (hsIframe) => {
        // Log iframe details
        console.log('HubSpot iframe detected:', hsIframe);
        console.log('Iframe attributes:', Object.fromEntries(
            Array.from(hsIframe.attributes).map(attr => [attr.name, attr.value])
        ));

        
        // Get iframe origin
        const iframeOrigin = new URL(hsIframe.src).origin;
        
        // Message handler for HubSpot form events
        const messageHandler = (event) => {
            if (event.origin !== iframeOrigin) return;

            // Debug: Log all messages from HubSpot iframe
            console.log('Received HubSpot message:', event.data);

            if (event.data?.type === 'hsFormCallback' &&
                event.data?.eventName === 'onFormReady' &&
                event.data?.data?.formId === FORM_ID) {
                
                // Send field update with corrected field name
                hsIframe.contentWindow.postMessage({
                    type: 'hsFormRequest', // This is typically correct for HubSpot
                    data: {
                        fields: [{ 
                            name: FIELD_NAME, 
                            value: 'example' 
                        }]
                    }
                }, iframeOrigin);
            }
        };

        window.addEventListener('message', messageHandler);
    };

    // Initial iframe detection
    const hsIframe = document.querySelector(IFRAME_SELECTOR);
    if (hsIframe) return handleFormReady(hsIframe);

    // Setup mutation observer for dynamic loading
    new MutationObserver((_, observer) => {
        const iframe = document.querySelector(IFRAME_SELECTOR);
        if (iframe) {
            handleFormReady(iframe);
            observer.disconnect();
        }
    }).observe(document.body, { childList: true, subtree: true });
});
</script>

<!-- HubSpot embed code -->
<script src="https://js-eu1.hsforms.net/forms/embed/{{someid}}.js" defer></script>
<div class="hs-form-frame" 
    data-region="eu1" 
    data-form-id="{{formid}}" 
    data-portal-id="{{portal}}">
</div>
</html>​

 



 

0 Upvotes
TomM2
Solution
Thought Leader | Platinum Partner
Thought Leader | Platinum Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hey @dash-flow-io  I can't definitely see this being a large pain point. I'd recomend sharing this with the product team through a feature request on the ideas forum here

Tom Mahon
Technical Consultant | Solutions Engineer | Community Champion
Baskey Digitial

Book a consultation

Did my post help answer your query? Help the community (and me) by marking it as a solution.


0 Upvotes
dash-flow-io
Member

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hi Baskey, i think there is typo, you wrote "can't" but I think you meant "can"?

0 Upvotes
TomM2
Thought Leader | Platinum Partner
Thought Leader | Platinum Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hi @dash-flow-io yep, you're correct, that is a typo. I have fat fingers and have to type a lot throughout my day. 
That still doesn't change my recomendation on opening this as a feature request to the product team however. 

Tom Mahon
Technical Consultant | Solutions Engineer | Community Champion
Baskey Digitial

Book a consultation

Did my post help answer your query? Help the community (and me) by marking it as a solution.


0 Upvotes
Mike_Eastwood
Recognized Expert | Gold Partner
Recognized Expert | Gold Partner

New Forms: How to fill hidden fields with JavaScript

SOLVE

Hi @dash-flow-io 

 

Recently I've seen forms int he wild removing the iFrame, using a new implementation.

 

I haven't been able to figure out when the changes happen.

 

To target a value in an iFrame this is what I used:

 

<!--[if lte IE 8]>
    <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js"></script>
<![endif]-->
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js" defer></script>
<script>
var change_me   = "123";
  
window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
    document.getElementById("hs-form-iframe-0").contentDocument.querySelector('input[name="change_me"]').value = change_me;
  }
});
</script>

 

But, as mentioned, I'm looking at changing this and using a new implementation (without the iFrame).

 

Have fun

Mike

Here to learn more about HubSpot and share my HubSpot Knowledge. I'm the founder of Webalite a Gold HubSpot Partner Agency based in Wellington, New Zealand and the founder of Portal-iQ the world's first automated HubSpot Portal Audit that helps you work smarter with HubSpot.

0 Upvotes
dash-flow-io
Member

New Forms: How to fill hidden fields with JavaScript

SOLVE

the embed code you use seems to be a legacy form. the new forms use different embedding.

0 Upvotes