Search code examples
javascripthtmldropdown

Dropdown in HTML is empty at initialization due to Javascript


I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.

It works very well, except that at the initialization the default value of the dropdown is an empty field.

I would need the first option to be displayed at initialization.

I guess it's easy but I don't know JavaScript at all. Could you please help?

Here is what the code looks like:

<select name="options" id='dropdown'>
  <option value="1">1st Option</option>
  <option value="2">2nd Option</option>
  <option value="3">3rd Option</option>
  <option value="4">4th Option</option>
 </select>


 <!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->

  <script type="text/javascript">

    var selectedItem = sessionStorage.getItem("SelectedItem");  
    $('#dropdown').val(selectedItem);

    $('#dropdown').change(function() { 
    var dropVal = $(this).val();
    sessionStorage.setItem("SelectedItem", dropVal);
    });
 </script>

Solution

  • I think you should check if SessionStorage Key exists or not.

    I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/

    Here is HTML Markup:

    <select name="options" id='dropdown'>
      <option value="0" selected>--- select here ---</option>
      <option value="1">1st Option</option>
      <option value="2">2nd Option</option>
      <option value="3">3rd Option</option>
      <option value="4">4th Option</option>
    </select>
    

    and JS Code

     let selectedItem = sessionStorage.getItem("SelectedItem");
    
     if (selectedItem) {
        $('#dropdown').val(selectedItem);
     } else {
       $('#dropdown').val(0);
     }
    
     $('#dropdown').change(function() { 
        let dropVal = $(this).val();
        sessionStorage.setItem("SelectedItem", dropVal);
     });
    

    Let me know if you face any issue with this.