Snippets

Sam Fonoimoana clientId.js

Created by Sam Fonoimoana
// get the cookie value
var getCookie = function(cookieName){
    return (name = new RegExp('(?:^|;\\s*)' + cookieName + '=([^;]*)').exec(document.cookie)) ? name.split(',')[1] : ''; 
};

// set a form field value with the value from a cookie
var setFormField = function(fname, cookie){
    // find all forms on the page (should only be 1)
    var formsCollection = document["forms"];
    if(formsCollection.length>1){console.log("extra forms detected")};
    // iterate through each form (should only be one), search for hidden input field by name and populate with client id
    for(var i=0;i<formsCollection.length;i++){
        var select;
        formsCollection[i][fname] === undefined ? select = [] : select = [formsCollection[i][fname]]; // if target hidden input does not exist than empty array else array with the input element 
        // look for the hidden input field and populate it
        if(select.length === 0){
            // if the target hidden input does not exist then create a new one
            console.log("Hidden input field doesn't exist - create a new one first then come back and try again.");
        } else {
            // if it already exists than go ahead and change the value to the cookie (for unbounce)
            console.log("Hidden input exists - will update the value.");
            select[0].value = cookie;
        }
    }
};

// do it
var _fname = "<YOUR FIELD NAME>";
setFormField(_name, getCookie('_ga'));

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.