0

I want to store selected option in cookie via javascript This is my code

var prevVal;
$("#paragraphSpaceOPtion").on("change",function(){
    var val = $(this).find('option:selected').val();
    $(".container-h div").text(`${val}`);
    $(".fancybox-container").hide();
    $("body").removeClass('compensate-for-scrollbar');
    $(".footer-phone").text(`${val}`);
    prevVal = val;
});

<select name="number" id="paragraphSpaceOPtion">
    <option class="option-1" value="">Your sity</option>
    <option class="option-1" value="city1">Paris</option>
    <option class="option-2" value="London">London</option>
</select>
  • Possible duplicate of [Session only cookies with Javascript](https://stackoverflow.com/questions/14196671/session-only-cookies-with-javascript) – nbk Sep 05 '19 at 17:58

1 Answers1

-1

Here are functions you can use for creating and retrieving cookies.

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

So for your example, you can use createCookie('myvalue', val, 7) to save value for one week.

ManUtopiK
  • 4,495
  • 3
  • 38
  • 52