'How to load localStorage value using fetch() on page load?
I have 2 html pages, index.html and dropdown-component.html
dropdown-component.html:
<select id="AssistSelectMenu">
<option value="assist/AK.html">Alaska</option>
<option value="assist/AL.html">Alabama</option>
<option value="assist/AZ.html">Arizona</option>
</select>
onclick of a button in index.html, I try to fetch the content of dropdown-component.html
Using the ff:
function fetchJXSelectMenu() {
fetch('dropdown-component.html')
.then(response => response.text())
.then(text => document.querySelector('#component-assist-jx-select-menu').innerHTML = text);
}
It is loaded in a div <div id="component-assist-jx-select-menu"></div>.
The problem is, the "component" it loads is a select/option that utilizes localStorage to remember the last selected option of the user.
It looks like this:
$(function () {
$('#AssistSelectMenu').change(function () {
localStorage.setItem('JXselect', this.value);
});
if (localStorage.getItem('JXselect')) {
$('#AssistSelectMenu').val(localStorage.getItem('JXselect'));
}
});
If I'm not using the fetch() method, the localStorage function works fine, but if I do use it, it fails to load the last selected option of the user on page load. I'm guessing this is because the browser has already finished rendering the page and can't process the localStorage for the newly loaded component.
So my question is how do I workaround this? I tried putting the script in the component but that didn't solve it at all.
Thank you in advance for any help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
