Applying cookies to <input>s with js-cookie

127 Views Asked by At

I wish to apply cookies to two inputs' default values. I am using GitHub's jscookie, and it would be preferable to have the answer using jscookie as well. I have an input at a default value of zero and I want it to default to the stored cookie for them after the first time answering it. E.g.

<input type="text" name="changeme" value="0">
<div id="submit">Submit</div>

JavaScript/JQuery with jscookie plugin:

$(document).ready(function() {
        if (Cookies.get("inputval") != undefined) {
                $('input[name="changeme"]').val(Cookies.get("inputval"));
        }
        $('#submit').on('click', function() {
                var inval = $('input[name="changeme"]').val();
                Cookies.set("inputval", inval { expires: 1, path: "" });
        });
});

And so after reloading the page I would expect the value to be what was initially entered. The cookies were saved however they weren't applied to the input. I've tried most every variation on the syntax I could think of, nothing has helped. Thanks in advance for the response!

1

There are 1 best solutions below

2
On BEST ANSWER

This line is causing a syntax error because you have missed a comma:

Cookies.set("inputval", inval { expires: 1, path: "" });
                             ^-- missing ',' here

Try the following:

$(function() {
    if( Cookies.get('inputval') ) 
    {
        $('input[name="changeme"]').val( Cookies.get('inputval') );
    }

    $('#submit').on('click', function() {
        Cookies.set("inputval", $('input[name="changeme"]').val(), { expires: 1, path: "" });
    });
});