APIs & Integrations

ehannscott
Member

Help Passing a cookie into Hubspot Hidden form field

I've read through other posts, but still haven't been able to figure this out correctly. Here's my situation:

 

I'm storing utm values into separate cookies. ex) "website_campaign" I then want to pass this into a hubspot form in a hidden field. I've currently got this code:

 

<!--[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"></script>
<script>
  hbspt.forms.create({
	portalId: "XXXXXX",
	formId: "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
      onFormSubmit: function($form) {
                jQuery('input[name="ga_campaign"]').val('test_ga_campaign').change()
    }
});
</script>

This code will insert a hard coded value of "test_ga_campaign" into the field I want it too. My question is how to I modify it so it passes the value of the website_campaign cookie?

 

I only have very minimal JS and jQuery Skills, and have gotten this far largely by following documentation in this forum and some trial and error, but am now a little stuck

0 Upvotes
1 Reply 1
WendyGoh
HubSpot Employee
HubSpot Employee

Help Passing a cookie into Hubspot Hidden form field

Hey @ehannscott,

 

Great work there!

 

When looking to retrieve cookie, you can use a javascript like this:

 

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

then call the function:

 

var value = readCookie('obligations');

 

Resources from: javascript - Get cookie by name - Stack Overflow and JavaScript - Cookies 

0 Upvotes