How to save input data with jQuery cookies

Jquery Cookies

As a UX designer and developer I work with clients of all sorts, and of course I receive all sorts of requests for web dev trickery. The other day I had a client request that stumped me … he had the need to save the users input data from a form so that if they refreshed and did not submit the form would be re-presented with the data that was input by the user. I know crazy, right? Not really, this is actually a great trick for a better user experience.

So after a few google searches I turned up this post on StackOverflow. Now the question was tagged with PHP, but the best answer was doing this using JavaScript and jQuery.

This ultimately creates a better user experience when filling out forms, not losing their information when refreshing or accidentally hitting the back button.

Here is the solution that worked best for me on how to save input data with jQuery:
The first 2 functions set and get the cookies:

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        c_value = unescape(c_value.substring(c_start, c_end));
    return c_value;

After that we need to grab the data being entered by the user and save it:

function saveValue(input) {
    var name = input.attr('name');
    var value = input.val();
function getValue(input) {
    var name = input.attr('name');
    var value = getCookie(name);
    if(value != null && value != "" ) {
        return value;

Now that you have those functions you can use jQuery to set the cookies with the data entered:

jQuery('input[type="text"], textarea').each(function(){
    var value = getValue(jQuery(this));
}).on('blur', function(){
    if(jQuery(this).val() != '' ) {

Leave a Reply



To set up a strategy call, please fill out your information and I will reply with a confirmed date and time along with the meeting details.

Best time to call?
In case that doesn't work, is there an alternative date and time?

Let's Work Together

Fill out the form below with your information, and I will be in touch. I really look forward to working together on your project.