I'm trying to keep the selected option in HTML after doing a refresh using local storage. I followed the example mentioned here Below is my code.
document.getElementById("interface-output").onchange = function() {
localStorage.setItem('selectedtem', document.getElementById("interface-output").value);
};
if (localStorage.getItem('item')) {
document.getElementById("selectedtem").options[localStorage.getItem('selectedtem')].selected = true;
}
<div class="row" id="ott-redirect-interface-selector">
<label>Output Interface</label><br>
<select id="interface-output" class="browser-default">
<option value="select">Select an interface</option>
<option value="eth0">eth0</option>
<option value="eth1">eth1</option>
</select>
</div>
I'm trying to keep the selected option in HTML after doing a refresh using local storage. I followed the example mentioned here Below is my code.
document.getElementById("interface-output").onchange = function() {
localStorage.setItem('selectedtem', document.getElementById("interface-output").value);
};
if (localStorage.getItem('item')) {
document.getElementById("selectedtem").options[localStorage.getItem('selectedtem')].selected = true;
}
<div class="row" id="ott-redirect-interface-selector">
<label>Output Interface</label><br>
<select id="interface-output" class="browser-default">
<option value="select">Select an interface</option>
<option value="eth0">eth0</option>
<option value="eth1">eth1</option>
</select>
</div>
Unfortunately this setting doesn't preserve the selected option after a refresh. Any suggestions please ?
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 15, 2016 at 22:40 Joseph WahbaJoseph Wahba 3472 gold badges9 silver badges20 bronze badges 3- Are you running the JS after the DOM has loaded? – user3310334 Commented Dec 15, 2016 at 22:43
- I'm extending an existing code base. Not too sure – Joseph Wahba Commented Dec 15, 2016 at 22:50
-
getElementById("selectedtem")
is looking for anid
that doesn't exist in your HTML. Did you meangetElementById("interface-output")
? – Paul Roub Commented Dec 16, 2016 at 19:56
1 Answer
Reset to default 5<html>
<body>
<div class="row" id="ott-redirect-interface-selector">
<label>Output Interface</label><br>
<select id="interface-output" class="browser-default">
<option id="select" value="select">Select an interface</option>
<option id="eth0" value="eth0">eth0</option>
<option id="eth1" value="eth1">eth1</option>
</select>
</div>
<script>
document.getElementById('interface-output').onchange = function() {
localStorage.setItem('selectedtem', document.getElementById('interface-output').value);
};
if (localStorage.getItem('selectedtem')) {
document.getElementById('interface-output').options[localStorage.getItem('selectedtem')].selected = true;
}
</script>
</body>
</html>