HubSpot form inputs are null on page load

I’m trying to implement populating hidden fields with cookie data on a non-HTML, embedded HubSpot form. However, I run into this error:

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

//Error text:
VM57621:1 Uncaught TypeError: Cannot read properties of null (reading 'value')
 at <anonymous>:1:53
(

This happens even when the form comes into view. In fact, the warning doesn’t go away until I inspect the element, find the hidden fields, and then try it again.

My code looks like this:

<script>
 // Get URL from cookie
 var campaignUrl = decodeURI(cookieUrl);
 // Get utm params
 var cookieParams = campaignUrl.split('?')[1];
 console.log(cookieParams);
 var individualParams = cookieParams.split('&')
 var cookieStorage = {}
 // loop through params and push to cookieStorage dictionary cookieStorage
 individualParams.forEach(function(param) {
 var paramKey = param.split('=')[0];
 var paramVal = param.split('=')[1];
 if (paramKey.includes('utm') || paramKey.includes('gtm')) {
 cookieStorage[paramKey] = paramVal;
 }
 })
 console.log(cookieStorage);

// attempt to substitute value of hidden fields with cookieStorage values
document.querySelector('input[name="utm_campaign"]').value=cookieStorage["utm_campaign"];
 document.querySelector('input[name="utm_medium"]').value=cookieStorage["utm_medium"];
 document.querySelector('input[name="utm_source"]').value=cookieStorage["utm_source"];
 document.querySelector('input[name="utm_term"]').value=cookieStorage["utm_term"];
</script>

This works as intended all the way up to setting the document.querySelector values because, as mentioned, these are null until I interact with the actual source code.

Hi @NVogel6,

Thank you for reaching out to the Community!

I wanted to tag in a couple of subject matter experts to see if they have any suggestions/ideas:

Hi @Phil_Vallender, @ManuelC, @Josh, do you have advice for @NVogel6? Thank you! :folded_hands:

Cheers
Mia, Community Team

Any updates here @Phil_Vallender @ManuelC @Josh? I’m running into this same issue in another project I’m working on with hidden fields and not using Google Tag Manager. It seems that no matter what I do, the code to the HS form is inaccessible to me until I interact with the HTML in either the Chrome or Safari dev tools.