0

I'm trying to set up a system on my site so that users who come through a custom link get tagged with a cookie that triggers a specific code to replace the default part of a signup form. The desired result is, in this example, for someone coming to http://example.com/?=mylink1 getting tagged with a cookie that changes the "value" attribute in any inputs with id #xcode to "X190". What I have so far:

Create cookie from query string:

  function cookieQuery() {
            var url = window.location.href;
            if(url.indexOf('?' + mylink1) = 1)
                document.cookie="cookie1";
    }

Check cookie and if true change attribute value with Jquery, if no cookie, do nothing:

function readCookie(cookie1) {
    var nameEQ = cookie1 + "=";
    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) 

            $("#xcode").attr("value","X190");
    }
    return null;
}   

I appreciate any help figuring this out!

Epleroma
  • 153
  • 6
  • 15

1 Answers1

1

You don't need to use a cookie unless you need to persist data on the users computer, you can use the url parameter by itself to change the form.

//page URL http:somewhere.com/index.html?foo=bar&baz=boaz var url = window.location.href;

//This function puts all of the params into a js object
function getParams(u){
    var theURL = u; 
    var params = {}; 
    var splitURL = theURL.split('?'); 
    if (splitURL.length>1 ){ 
        var splitVars = splitURL[1].split('&'); 
        for(var i = 0; i < splitVars.length; i++){ 
            splitPair = splitVars[i].split('='); 
            params[splitPair[0]] = splitPair[1]; }

        return params;
    }
    return false;
}

params = getParams(url);

//Check if there are any params
if (params) {
    var foo = params.foo;
    //Use foo to make decision here
}
Ron Sims II
  • 566
  • 5
  • 10
  • Thank you, but the thing here is that I do need this to follow the user across the site. There are forms with the #xcode input on almost every page, so if a user enters the homepage though a custom link http://example.com/?=mylink1 and then navigates to another page, I still need the dynamic change to happen in an any page that the person ends up signing up on. Is there any way to do this without a cookie? – Epleroma Sep 18 '14 at 13:08