Skip to content
Advertisement

Retain Values in two related Dropdown List after Page refresh

I have two dropdown lists where on changing the value in the first dropdown, the second dropdown is appended with the values based on the value selected in the first dropdown.

My code is:

$('#orgdropdown').on('change', function() {
  var selectVal = this.value;
  switch (selectVal) {
    case 'Test Company 1':

      $("#datasources option[value='test']").remove();
      $('#datasources').append(`<option value="Test1">TEST1</option>`);
      $('#datasources').append(`<option value="Test2">Test2</option>`);


      break;
    case 'Test Company 2':
      // console.log('Test Company 1');
      $("#datasources option[value='Test1']").remove();
      $("#datasources option[value='Test2']").remove();
      $('#datasources').append(`<option value="test3">Test3 Data source</option>`);
      break;
    default:
      $("#datasources option[value='Test1']").remove();
      $("#datasources option[value='Test2']").remove();
      $("#datasources option[value='Test3']").remove();


  }

});

$('#datasources').on('change', function() {
  window.location = 'https://location' + this.value;

});
<select class="orgdropdown" id="orgdropdown" name="organization">
  <option value="Test Company 1">Test `Company` 1</option>
  <option value="Test Company 2">Test Company 2</option>
</select>

<select class="datadropdown" id="datasources" name="data">
  <option value="https://location" selected="">Manage Organization Data Source</option>
</select>

Could anyone please suggest me how to retain the selected values in both dropdowns after page refresh?

Advertisement

Answer

Use localStorage.

SO Stacksnippets do not allow them, but try this on your server

$('#orgdropdown').on('change', function() {
  var selectVal = this.value;
  localStorage.setItem("orgdropdown",selectVal);
  switch (selectVal) {
    case 'Test Company 1':

      $("#datasources option[value='test']").remove();
      $('#datasources').append(`<option value="Test1">TEST1</option>`);
      $('#datasources').append(`<option value="Test2">Test2</option>`);


      break;
    case 'Test Company 2':
      // console.log('Test Company 1');
      $("#datasources option[value='Test1']").remove();
      $("#datasources option[value='Test2']").remove();
      $('#datasources').append(`<option value="test3">Test3 Data source</option>`);
      break;
    default:
      $("#datasources option[value='Test1']").remove();
      $("#datasources option[value='Test2']").remove();
      $("#datasources option[value='Test3']").remove();


  }

});

$('#datasources').on('change', function() {
  window.location = 'https://location' + this.value;

});
$(function() {
  const orgdropdownval = localStorage.getItem("orgdropdown");
  if (orgdropdownval) {
    $('#orgdropdown').val(orgdropdownval)
    $('#orgdropdown').trigger("change");
  }
})
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement