Reputation: 57
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
Reputation: 28434
The code has several issues:
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.else-if
instead of comparing the value three times.onchange
in the html
element, so it should not be declared in the function.select.value
where select is the html
element in this exampleThe 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
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