Nicoletta
Nicoletta

Reputation: 57

Dropdown select reloads to first option when reloaded

Hello I am having problems with the select dropdown. I am trying to store the value but it's not working. I have looked at other questions already but with no luck.

Here is a fiddle:

function selectCss(element) {
  const a = element.options[element.selectedIndex].value;

  document.getElementById("change").onchange = function() {
    localStorage['colorPick'] = element.options[element.selectedIndex].value;
  }
  window.onload = function() {
    if (localStorage['colorPick'])
      document.getElementById("change").value = localStorage['colorPick'];
  }

  if (a == "Theme 1") {
    document.body.style.background = "pink";

  }

  if (a == "Theme 2") {
    document.body.style.background = "blue";
  }

  if (a == "Theme 3") {
    document.body.style.background = "yellow";
  }
}
body {
  background: pink;
}
<select  id="change" name="colorPick"  onchange="selectCss(this)">
  <option selected value="Theme 1">Theme 1</option>
  <option value="Theme 2">Theme 2</option>
  <option value="Theme 3">Theme 3</option>
</select>

Upvotes: 0

Views: 377

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28434

The code has several issues:

  1. The value of the select and the color should be set if there's an item in the localStorage. This should be done at first instead of doing it inside the function.
  2. It's better to use else-if instead of comparing the value three times.
  3. The listener is already set onchange in the html element, so it should not be declared in the function.
  4. You can define the element once and use it all the time.
  5. You can get the selected value using select.value where select is the html element in this example

The working solution with the proper modifications would be as follows:

let select = document.getElementById("change")
if (localStorage['colorPick']){
     select.value = localStorage['colorPick'];
     selectCss();
}
function selectCss() {
     const a = select.value;
     localStorage['colorPick'] = a;
     if (a == "Theme 1") {
          document.body.style.background = "pink";
     }else if (a == "Theme 2") {
          document.body.style.background = "blue";
     }else if (a == "Theme 3") {
          document.body.style.background = "yellow";
     }
}
body {background: pink;}
<select  id="change" name="colorPick"  onchange="selectCss()">
     <option selected value="Theme 1">Theme 1</option>
     <option value="Theme 2">Theme 2</option>
     <option value="Theme 3">Theme 3</option>
</select>

Upvotes: 1

Syed Jailani
Syed Jailani

Reputation: 161

Use setItem method To store to local storage.

localStorage.setItem("colorPick", element.options[element.selectedIndex].value);

Use getItem method to retrieve

let colorPick = localStorage.getItem("colorPick")

Upvotes: 0

Related Questions