I have multiple select option dropdowns and want to use local storage to save the user's choices once they have been selected. This is an example of the HTML:
<div class="sel_container">
<select onchange="saveChoice()" id="select_color" class="test">
<option value="">Choose color</option>
<option value="red">red</option>
<option value="blue">blue</option>
<option value="green">green</option>
</select>
<select id="select_type" class="test" onchange="saveChoice()">
<option value="">Choose size</option>
<option value="small">small</option>
<option value="medium">medium</option>
</select>
</div>
I used this code from another post I found and it works to save one of the selections:
$(function() {
$('#select_color').change(function() {
localStorage.setItem('todoData', this.value);
});
if(localStorage.getItem('todoData')){
$('#select_color').val(localStorage.getItem('todoData'));
}
});
I am new with javascript and after doing some reading it seems like I need to do a JSON stringify, but I am really confused about the syntax of this. I tried using this and it does not work:
var obj = {
"#select_color": this.value,
"#select_type": this.value
}
var stringifyObj = JSON.stringify(obj);
Any help with this is much appreciated! Thanks!
You don't need to use an object nor JSON for this specifically. What you could do is improve your code by making it more generic so that it works for any instance of a
select
.You have given them both the
.test
class, so you can select by that. You can then set the value in localstorage keyed by theid
of theselect
, which can be retrieved on page load. Try this;Working example