1

I am having some trouble creating and getting a cookie with multiple values inside. Okay, what I would like to do, is to create a cookie with a forms input values in it when a submit button is clicked. Then when the same user revisits the site, the form will be autofilled with what the user typed in last time.

My html:

<form id="formen">
<fieldset>
    <legend>Login</legend>
    <label for="firstname" class="label">Firstname</label>
    <input type="text" name="firstname" id="firstname" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Lastname</label>
    <input type="text" name="lastname" id="lastname" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Address</label>
    <input type="text" name="third" id="address" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">City</label>
    <input type="text" name="city" id="city" class="text" maxlength="30" data-sayt-exclude/>
    </br></br>
    <label for="lastname" class="label">Zipcode</label>
    <input type="number" name="zipcode" id="zipcode" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">E-mail</label>
    <input type="email" name="email" id="email" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Phone</label>
    <input type="number" name="phone" id="phone" class="text" maxlength="30" />
    </br></br>
    <input type="submit" name="submit" value="Remember Me" id="remember"/>
</fieldset>
</form>

My javascript/jQuery:

$(document).ready(function () {
var date = new Date();
date.setTime(date.getTime() + (60 * 1000));

if ($("#remember").click(function () {
    $.cookie('firstnameCookie', $firstnameVariable.val(), { expires: date });
    $.cookie('lastnameCookie', $lastnameVariable.val(), { expires: date });
    $.cookie('addressCookie', $addressVariable.val(), { expires: date });
    $.cookie('cityCookie', $cityVariable.val(), { expires: date });
    $.cookie('zipcodeCookie', $zipcodeVariable.val(), { expires: date });
    $.cookie('emailCookie', $emailVariable.val(), { expires: date });
    $.cookie('phoneCookie', $phoneVariable.val(), { expires: date });
}));

//set the value of the cookie to the element
var $firstnameVariable = $("#firstname").val($.cookie("firstnameCookie"));
var $lastnameVariable = $("#lastname").val($.cookie("lastnameCookie"));
var $addressVariable = $("#address").val($.cookie("addressCookie"));
var $cityVariable = $("#city").val($.cookie("cityCookie"));
var $zipcodeVariable = $("#zipcode").val($.cookie("zipcodeCookie"));
var $emailVariable = $("#email").val($.cookie("emailCookie"));
var $phoneVariable = $("#phone").val($.cookie("phoneCookie"));
});

This code actually does the trick. It saves the different input values, and autofills when user revisits the site.

The only problem is that I don't want to create a new cookie for each input value. Is it possible to create just one cookie with each of the inputs values in it, and get it to autofill the different input fields?

Hope someone can help me! Can't figure it out.. Thx

PitaPakker
  • 11
  • 1

2 Answers2

0

Concatenate the form values into a string before saving the cookie and split when you have to assign it. Those are functions I use to concatenate and split:

    var splitQueryString = function (q) {
        var pars = q.split("&");
        var qq = {};
        var i = 0;
        for (i = 0; i < pars.length; i++) {
            var ret = pars[i].toString().split("=");
            qq[ret[0]] = decodeURIComponent(ret[1]);
        }
        return qq;
    };

    var getQueryString = function (pars) {
        var q = '';
        var value;
        var key;
        for (key in pars) {
            if (pars.hasOwnProperty(key)) {
                value = pars[key];
                if (!(value === null)) {
                    q += "&" + key + "=" + encodeURIComponent(value);
                }
            }
        }

        if (q.length > 0) {
            //remove first
            q = q.substr(1);
        }

        return q;
    };

Your code could become something like:

    if ($("#remember").click(function () {
        var pars = {};
        pars.firstnameVariable = $firstnameVariable.val();
        pars.lastnameVariable = $lastnameVariable.val();

        var cookie = getQueryString(pars);
        $.cookie('formCookie', cookie, { expires: date });
       }));

  //set the value of the cookie to the element
  var pars = splitQueryString($.cookie("formCookie"));
  var $firstnameVariable = $("#firstname").val(pars.firstnameVariable);
  var $lastnameVariable = $("#lastname").val(pars.lastnameVariable);
Draykos
  • 753
  • 6
  • 16
  • I am trying to use your code to set a cookie. I keep getting an "Uncaught TypeError: Cannot read property 'split' of undefined" error in the console. Any ideas why it is not working? – Colin Jun 24 '19 at 16:50
  • @Colin do you have installed the "cookie" jquery plugin on your project? https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery https://github.com/carhartl/jquery-cookie – Draykos Jun 25 '19 at 12:39
  • Yes, version 1.4.1 of the cookie plugin is installed. Could it be anything else? – Colin Jun 25 '19 at 13:36
  • reason is cookie must be already set. My code was a sample based on the code on the question. Here is a working sample https://jsfiddle.net/9r0zct8f/1/ Vote my answer if it's working now – Draykos Jun 25 '19 at 16:19
  • When I use the fiddle, I get these errors in the Console: Uncaught ReferenceError: $firstnameVariable is not defined and Uncaught TypeError: Cannot read property 'split' of undefined – This happens after I cleared all the cookies for jsfiddle.net from Chrome. – Colin Jun 26 '19 at 13:45
0

Store the data by converting the object to a string

var obj = {
    "firstname" : $("#firstname").val(),
    "lastname" : $("#firstname").val()
};
$.cookie('data', JSON.stringify(obj), { expires: date });

And when you read it out:

var data = $.cookie("data"),
    obj = data ? JSON.parse(data) : "";
Object.keys(obj).forEach(function(key){
    $("#" + key).val(obj[key]);
});

Personally I would use localstorage and not a cookie.

epascarello
  • 185,306
  • 18
  • 175
  • 214