How do I load values from Localstorage to multiple dynamically loaded dependent dropdowns?

I know this may be a simple problem for many of you, but I am at a stand still and don’t have the skills to complete this task. I have been unable to find a functioning answer anywhere on the web from any of my research. I have several groups of dependent dropdown select/options (three per group) that are loaded via ajax from a server. The first dropdown in each group functions. However the second and third do not. I have two (2) problems. The first problem is I can not get the values in localstorage to reload back into the perspective dropdown list following a page refresh. The second problem is the value that is stored in localstorage is not the correct value that was actually selected in the dropdown list. It appears that the localstorage is either storing the last value in the dropdown list or the first value in the dropdown list. The localstorage in the second dropdown always stores the last value and the third dropdown always stores the first value.


Please excuse my code. It is NOT very efficient. I am still learning how to write better code. :disappointed: I will try to condense my code as best as I can here so you can see what is happening. I would appreciate every tip you good programmers can give me on this problem and on code writing in general. The jquery and ajax call is as follows;

$(document).ready(function () {
    $('.country').on('change', function () {
        var countryId = $(this).val();            
        var state_select = $(this).closest('form').find('.state');
        var city_select = $(this).closest('form').find('.city');            

        if (countryId) {
            $.ajax({
                type: 'POST',
                dataType: 'json', 
                url: 'ajaxData.php',
                data: {
                    country_id: countryId
                },
                success: function (r) {
                    console.log('States', r);                        

                    if (r.status) {
                        r.data.forEach(function (state) {
                            $(state_select).append(`<option value="${state.id}">${state.name}</option>`);                  

                            $('.state').each(function(r) {
                                var stateList = $(state);
                                var thisSelection = $(this);
                                var thisId = thisSelection.attr('id');
                                var storageId = 'state-' + thisId;
                                var storedInfo = localStorage.getItem(storageId);

                                if( storedInfo ) {
                                    var rememberedOptions = storedInfo.split(',');
                                    thisSelection.val( rememberedOptions );
                                }


                                thisSelection.on('change', function(e) {                                    
                                    var selectedOptions = [];
                                    thisSelection.find(':selected').each(function(i) {
                                        var thisOption = $(this);
                                        selectedOptions.push(thisOption.val());
                                    });
                                    localStorage.setItem(storageId, (state.name));

                                });
                            });                                
                        });

                    } else {                            
                        $(state_select).html('<option value="" selected="selected">Unavailable</option>');
                        $(city_select).html('<option value="" selected="selected">Unavailable</option>');
                    }

                }
            })
        };
    }); 

    $('.state').on('change', function () {
        var stateId = $(this).val();            
        var city_select = $(this).closest('form').find('.city');

        if (stateId) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'ajaxData.php',
                data: {
                    state_id: stateId
                },
                success: function (r) {
                    console.log('Cities', r);

                    if (r.status) {
                        r.data.forEach(function (city) {
                            $(city_select).append(`<option value="${city.id}">${city.name}</option>`);                    

                            $('.city').each(function(i) {
                                var stateList = $(city);
                                var thisSelection = $(this);
                                var thisId = thisSelection.attr('id');
                                var storageId = 'city-' + thisId;
                                var storedInfo = localStorage.getItem(storageId);

                                if( storedInfo ) {
                                    var rememberedOptions = storedInfo.split(',');
                                    thisSelection.val( rememberedOptions );
                                }

                                thisSelection.on('change', function(e) {                                    
                                    var selectedOptions = [];
                                    thisSelection.find(':selected').each(function(i) {
                                        var thisOption = $(this);
                                        selectedOptions.push(thisOption.val());
                                    });
                                    localStorage.setItem(storageId, (city.name));
                                });
                            });                                
                        });
                    } else {                            
                        $(city_select).html('<option value="" selected="selected">Unavailable</option>');
                    }
                }
            })
        };                       
    });   
    });  

The HTML markup is as follows;

<form id="form1" autocomplete="off">
    <select id="country1" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state1" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city1" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>
<form id="form2" autocomplete="off">
    <select id="country2" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state2" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city2" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>
<form id="form3" autocomplete="off">
    <select id="country3" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state3" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city3" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>

I have tried to stringify the “setItem” and parse the “getItem” such as;

 localStorage.setItem(storageId, JSON.stringify(state.name));
  var item = JSON.parse(localStorage.getItem("storageId"));
  var item = JSON.parse(localStorage.getItem("xyz")); //keys of items in localstorage

can anybody help me to fix this problem and help me to understand what is going on?? :banghead:

One of these things is not like the other…

Are you storing a JSON, or are you storing a CSV? Because your code says you’re doing both.

Hello m_hutly,
I am trying to use json (see below). Other than me being a newbie, I have been stabbing in the dark at this for quite sometime now. Do you see where my problem is?

if (countryId) {
            $.ajax({
                type: 'POST',
                dataType: 'json', 
                url: 'ajaxData.php',
                data: {
                    country_id: countryId
                },

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.