I have a HubSpot contact form integrated into my WordPress site. The form works fine and redirects users to a thank you page after submission. However, I need to capture the email addresses that users enter in the form so I can hash them and send the data to Google Analytics for enhanced conversions.
I hit the same timing issues on a client project. Your script’s running before HubSpot finishes rendering the form elements, so getElementById returns null. Don’t try attaching listeners to elements that don’t exist yet. Use HubSpot’s form API callbacks instead - they guarantee the form’s fully loaded. I’d go with onBeforeFormSubmit since it fires right before submission and lets you grab form data without messing up the submit process. You can also combine it with form validation to only capture valid emails. One heads up - make sure your dataLayer push finishes before the form actually submits, or your tracking might not fire because of page navigation timing.
Hit this exact same issue 6 months ago with enhanced conversions tracking. Your current approach won’t work because HubSpot dynamically generates form elements - they’re not there when your script runs. What fixed it for me was using the onFormSubmitted callback instead of intercepting the submit event. onFormSubmitted fires after validation but before the actual submission: javascript hbspt.forms.create({ region: "eu1", portalId: "30194082", formId: "598e3b42-87d2-5c8a-a4b4-d82f6963bd07", onFormSubmitted: function($form, data) { // data contains all form field values var emailValue = data.email; dataLayer.push({ 'event': 'contact_form_submit', 'enhanced_conversion_data': {"email": emailValue} }); } }); The data parameter already has all your form field values - no need to hunt for DOM elements. Been using this across multiple sites with zero issues.
Your main problem is calling userEmail.value() as a function when it should be userEmail.value as a property. But there’s a better way - use HubSpot’s built-in event callbacks instead of trying to grab DOM elements directly.
HubSpot forms have an onFormSubmit callback that fires before the form submits and gives you access to the form data. Here’s how to modify your form code:
try using the onFormReady callback to attach your event lissners - hubspot loads everything first, so the DOM elements are actually ready when you access them. Also, check the netwrk tab in devtools to see exactly what data gets sent on submit. Should help debug whatever’s going wrong with your currnt setup.