Skip to content
Advertisement

Retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list

I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere.

This is the code, the dropdown has a list of years from 2020 to the current year.

I store the year in local storage on change and in Chrome Dev Tools you can see how the stored variable changes when other years are chosen from the dropdown.

So far so good. But when I try to retrieve the year in the userSelectedYearStorage variable the last console.log line won’t show. What am I doing wrong? Thanks!

    <body>
      <div id="app">
        <select id="yearSelection">
          <option value="0" selected>Select a year</option>
        </select>
      </div>
    
          <script>
    
            var yearSelection = document.getElementById("yearSelection");
            var currentYear = new Date().getFullYear();
            for (let y = 2020; y <= currentYear; y++) {
              var element = document.createElement("option");
              element.textContent = y;
              element.value = y;
              yearSelection.appendChild(element);
            }
        
            var userSelectedYear = 0;
            $("#yearSelection").on("change", function () {
              userSelectedYear = this.value;
              console.log("userSelectedYear inside on change: " + userSelectedYear);
              localStorage.setItem("userSelectedYear", userSelectedYear);
            });
        
            var userSelectedYearStorage = localStorage.getItem('userSelectedYear')
//this line below won't be printed:
            console.log("userSelectedYear outside on change: " + userSelectedYearStorage);
        
          </script>
        </body>

Answer

That’s because when the page is first loaded, localStorage.getItem('userSelectedYear') equals null (it is not yet set). It only gets set when the change event is triggered. You can fix this by giving userSelectedYearStorage a default value like so

// userSelectedYear defaults to 0
var userSelectedYearStorage = localStorage.getItem('userSelectedYear') ?? userSelectedYear;
Advertisement