I’m trying to save the "selected" option from the <select>
HTML tag to the localStorage, so when I refresh the page the last selected option is selected. I can see that it’s saved in the console.log, but it’s not working on the page load. How can I make it work?
<select class="multiply_ing">
<option value="0.5">0.5x</option>
<option value="1" selected>1x</option>
<option value="1.5">1.5x</option>
<option value="2">2x</option>
<option value="2.5">2.5x</option>
<option value="3">3x</option>
<option value="4">4x</option>
<option value="5">5x</option>
<option value="6">6x</option>
<option value="8">8x</option>
<option value="10">10x</option>
</select>
<p class="portion" data-val="<?php echo $portion; ?>"></p> <!-- PHP Generated value, let's just say it's "1" -->
<div class="ingredient">
<p data-val="1"></p>
<p data-val="5"></p>
<p data-val="6"></p>
</div>
<script>
$(function() {
$(".multiply_ing").on("change", function() {
let multiply_val =+ this.value;
$('.ingredient p:nth-child(1)').each(function() {
let ing =+ this.dataset.val;
this.innerHTML = ing * multiply_val;
});
$('.multiply_ing option').each(function() {
let multi_opt = $(this).val();
let portion = parseFloat(document.querySelector(".portion").dataset.val);
let portions = multi_opt * portion;
});
let portion =+ document.querySelector(".portion").dataset.val;
document.querySelector(".portion").innerHTML = portion * multiply_val;
}).change();
jQuery($ => {
let $select = $('.multiply_ing');
// get on load
$select.val(localStorage.getItem('value') || 1); // 1 = default value
$select.on('change', e => {
localStorage.setItem('value', e.target.value);
});
});
});
</script>
Note: there is more code than in this example, but it’s irrelevant to the problem.
2
Answers
To do what you require you can just use
val()
to both get and set the value of the select when required:Also note that the
each()
in your example is doing nothing and can be removed. In addition,multiply_val
is not defined anywhere.As a general rule, if you’re going to incur the performance penalty of loading jQuery in to the DOM, then you’re better off making use of it everywhere. Mixing JS and jQuery just leads to confusion.
To store value in localStorage you have to use key value pair like this localStorage.setItem(‘selectedValue’,yourValue) and to get value use key to access the saved value localStorage.getItem(‘selectedValue’)
for working code you can see this demo