0

There have been previous questions surrounding this, however I want to know if its possible to save the whole configuration of the html select in a cookie/localStorage. By the whole configuration I mean all of the options that are currently in the select, and which option is selected.

And then load this configuration back from the cookie.

From previous questions, I currently save the select element using an onChange listener, which saves the element like:

$('#chosen-url').on("change", function () {
    saveToBrowserCookies("settings_select", this);
});

function saveToBrowserCookies(key, value) {
    document.cookie = key + "=" + value + "; path=/";
}

And then load the select like so (on initialization):

var savedSelect = getFromBrowserCookies("settings_select");
    if (savedSelect) {
        var select = document.getElementById("chosen-url");
        select.value = savedSelect;
}

function getFromBrowserCookies(key) {
    var cookies = {}
    var all = document.cookie;
    var value = null;

    if (all === "") { return cookies }
    else {
        var list = all.split("; ");
        for (var i = 0; i < list.length; i++) {
            var cookie = list[i];
            var p = cookie.indexOf("=");
            var name = cookie.substring(0, p);

            if (name == key) {
                value = cookie.substring(p + 1);
                break;
            }
        }
    }
    return value;
}

However this doesn't work.

H_Lev1
  • 253
  • 4
  • 18

1 Answers1

0

You can save anything in storage or in cookie, as long as it is a string. So in your case I'd recommend:

  1. Get all your select options and currently selected value and create an object with structure that would be easy to understand.
  2. Stringify this object to JSON form with JSON.stringify.
  3. Save json string in cookie or in LS.
  4. After reload, get saved json, read it with JSON.parse and take all needed information from the object.
  5. Recreate select element and set its chosen value.

I think that controlling select input per se is outside of the scope of this question, especially because we don't know if you are programming in pure js or in some kind of framework. But there are many informations on how to control select inputs on the web, e.g. here you can find decent answers on "how to set select value programatically".

Edit: you edited your question, so I will also add something to my response. You are trying to save whole "this" as cookie. I am not a big fan of jquery, but I guess that "this" is not necessarily the selected value. It may be a whole DOM object or change event maybe. Try logging out "this" and see what it is. You need to save string in a cookie.

Also, check in developer tools if the cookie was saved.

Last but not least, using break in a for loop is questionable. You can try using list.find instead.

Patryk Wlaź
  • 493
  • 5
  • 11