2

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 ?

3
  • Are you running the JS after the DOM has loaded? Commented Dec 15, 2016 at 22:43
  • I'm extending an existing code base. Not too sure Commented Dec 15, 2016 at 22:50
  • getElementById("selectedtem") is looking for an id that doesn't exist in your HTML. Did you mean getElementById("interface-output")? Commented Dec 16, 2016 at 19:56

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

I tried so but it gives me this error when I do the refresh: uncaught typeerror cannot read property 'options' of null
I added an id for select, too. Can you copy & paste all of this in a new file and open it with your browser?
I have a php form containing this dropdown, Now the form is not getting submitted. Any possible reason?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.