How to change selectedIndex from a dropdown populated with Ajax?

I have 3 dropdown lists that contains Regions,Locations,Sublocations of a country.
Im using Ajax to populate Locations And Sublocations lists after someone select something from first list.

Now to my issue:

Im using LocalStorage so when the page is refreshed i can keep the values and auto repopulate the lists with the last selected values.

The lists are sucessfuly populated but it fails to change the selectedIndex
(“Select a Town/Select a Subloc” are selected).

I tried every single way i found in stackoverflow on how to change selectedIndex and none of them worked as also none of them threw me an error.
So i can assume there is an issue with ajax ?
Something like js change the selectedIndex but ajax call rechange it back even if the ajax is called earlier than first.Could be something like that be possible ?

jQuery:

jQuery(document).ready(function(){
 if(localStorage) {
  if(localStorage.regions) {
  jQuery('#region_h').val(localStorage.regions);
  alert(localStorage.regions);
  getlocations_main(localStorage.regions); //ajax call for locations
  }
  if(localStorage.locations) {
    jQuery('#location_h').val(localStorage.locations);
    jQuery('#location_h option').eq(this.selectedIndex).prop('selected',true);
    alert(localStorage.locations);
    getsublocations_main(localStorage.locations); //ajax call for subloc
  }
  if(localStorage.subloc){
    jQuery('#subloc_h option').eq(this.selectedIndex).prop('selected',true);
  }

}
});

HTML:

<div class="row rowInput_spiti360">
 <div class="ie_fix_select_spiti360" >
  <div id="location_add_yo" class="mainselection" >
   <select class=" searchcategory" name="location_h" id="location_h" onchange="getsublocations_main(this.options[this.selectedIndex].value)">
    <option selected="selected" value="-1">Select a Town:</option>
   </select>
  </div>
 </div>
</div>  

<div class="row rowInput_spiti360">
 <div class="ie_fix_select_spiti360" >
  <div id="sublocation_add_yo"  class="mainselection" >
   <select id="subloc"  name="subloc" class=" searchcategory">
    <option selected="selected" value="-1">Select a sublocation:</option>
   </select>
  </div>
 </div>
</div> 


Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.