Search code examples
javascriptjquerypugselectedindex

How would I reload a page with a certain selectedIndex automatically selected from a dropdown list?


I have an external list that is being read to form the values in the select list I have on my webpage. When an item is selected it updates 3 bar graphs that are located in another area of code. I use setItem() under the on(change) function to locally save the selectedIndex value of the list. Then in the top part of the code I use getItem() to get this same index value and set it equal to the variable id. I have my page automatically refreshing every 30 seconds. I want to take the value of "idx" and have it automatically select that same index when the page reloads. So that it reloads with the last selected index, instead of resetting to being unselected.

.script
    window.onload = function() {
      var idx = localStorage.getItem(document.title.toLowerCase() + '-selectedIndex');
      console.log('last selected index : ' + idx);
    //*****what would I put here that uses the value idx to have the same index automatically selected when the page reloads
};


$('#foo').on('change', function(context) {


  var bar1 = $('#progressbar1');
  var bar2 = $('#progressbar2');
  var bar3 = $('#progressbar3');


  localStorage.setItem(document.title.toLowerCase() + '-selectedIndex', this.selectedIndex);

  bar1.val(globalSheetResults1[this.selectedIndex]);
  bar2.val(globalSheetResults2[this.selectedIndex]);
  bar3.val(globalSheetResults3[this.selectedIndex]);

Solution

  • You just need to set the selectedIndex of your option element on the page load, and then fire the change event. So, something like:

    document.getElementById('foo').selectedIndex = idx;
    $('#foo').change();