Skip to content Skip to sidebar Skip to footer

Reset Dropdown List On Click

I have this simple dropdown menu that display provinces and cities. On load it display first the provinces, when I select one province it will display the cities. What I want is af

Solution 1:

Add province and city to localStorage during the time of option selection. And assign the values to new variable after the selection process is completed. Then remove the province and city from localstorage for preparing selection box for the next updation Js file

functionshowLocalStorageValues(){
  alert(localStorage.getItem("selectedProvinceCity"));
}

functionloadProvince(){
   $("#provinceCity").html("<option value=''>Select province</option>");
  for (var i=0; i<province.length; i++){
    $("#provinceCity").append("<option value='"+province[i]["id"]+"'>"+province[i]["name"]+"</option>");
  }
}

$(document).ready(function(){
  $("#show").click(function(){
    showLocalStorageValues();
  });
  loadProvince();
  $("#provinceCity").change(function(){
    var selectedText = $("#provinceCity option:selected").text();
    if (localStorage.getItem("selectedProvince") === null) {
      localStorage.setItem("selectedProvince", selectedText);
    }elseif (localStorage.getItem("selectedCity") === null){
      localStorage.setItem("selectedCity", selectedText);
      loadProvince();
      localStorage.setItem("selectedProvinceCity", localStorage.getItem("selectedProvince")+ "-" +selectedText);
      localStorage.removeItem('selectedProvince');
      localStorage.removeItem('selectedCity');
    }
    for (var i=0; i<province.length; i++){
      if ($(this).val() == province[i]["id"]){
        $("#clearBtn").show();
        var cities = province[i]["city"];
        $("#provinceCity").html("<option value=''>Select City</option>");
        for (var j=0; j<cities.length; j++){
          $("#provinceCity").append("<option value='"+cities[j]["id"]+"'>"+cities[j]["name"]+"</option>");
        }
      }
    }
  });
});

var province=[ 
  {
    "id": "820000",
    "name": "P1",
    "city": [ 
      {
        "id": "820001", "name": "C1P1"
      },
      {
        "id": "820002", "name": "C2P1"
      },
      {
        "id": "820003", "name": "C3P1"
      }
    ]
  },
  {
    "id": "830000",
    "name": "P2",
    "city": [ 
      {
        "id": "830001", "name": "C1P2"
      },
      {
        "id": "830002", "name": "C2P2"
      },
      {
        "id": "830003", "name": "C3P2"
      }
    ]
  }
];

Html file

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="provinceCity"><optionvalue=''>Select province</option></select><buttonid="show">show saved values</button>

Post a Comment for "Reset Dropdown List On Click"