0

How I can use that code with two dropdown menus? Actually when I reload the page the first dropdown menu stays like I want but the second one no. Thanks. Sorry to ask, Im new in all this incredible world!

var init = function () { strong text var sel = $("select"), but = $("button");

    var clearSelected = function () {
      sel.find(":selected").prop("selected", false);
    };
  
    if (localStorage.getItem("pref")) {
      var pref = localStorage.getItem("pref");
      clearSelected();
      //set the selected state to true on the option localStorage remembers
      sel.find("#" + pref).prop("selected", true);
    }
  
    var setPreference = function () {
      //remember the ID of the option the user selected
      localStorage.setItem("pref", sel.find(":selected").attr("id"));
    };
  
    var reset = function () {
      clearSelected();
      localStorage.setItem("pref", undefined);
    };
  
    sel.on("change", setPreference);
    but.on("click", reset);
  };
  $(init);
  **strong text**

1 Answers1

0

I think .filter is what your need here. See this
.find will return the first element it founds that responds to the criteria you give. That's why your first dropdowm list is correct and not the second.
Also, for your storage, I guess you have 2 choices:

  • Set an item for the first dropdown menu, and another one for the second one that you can handle separatly.
  • Set only one item but containing an array of the values selected. With this solution you would have to set the item with an object as so

Hope I helped.

EDIT

I think this should do the math

Bejita
  • 116
  • 4
  • Thank you so much for the answer but I still do not get it. Can you give me an example, please? Sorry to bother you. I appreciate your help. – Andres Pelaez Jul 18 '21 at 00:46
  • Since I'm bad with my explanations, I've made you a codesandbox with comments. Check edits on my answer – Bejita Jul 18 '21 at 02:56
  • You don't know how I appreciate that. Thank you so much! I was fighting against it all day! Seriously, thank you so much. – Andres Pelaez Jul 18 '21 at 03:08