Im working on a select box which displays province and cities and I decided to to use the code from w3school which converts your select tag to divs so that I can apply more css.
my problem is I cant load the data from JSON to that custom select box, and also the functionalities I made.
function loadProvince(){
$("#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(){
loadProvince();
$("#provinceCity").change(function(){
var selectedText = $("#provinceCity option:selected").text();
if (selectedText != 'Select province') {
if (localStorage.getItem("selectedProvince") === null) {
localStorage.setItem("selectedProvince", selectedText);
}else if (localStorage.getItem("selectedProvince") !== null) {
localStorage.setItem("selectedCity", selectedText);
var selectedProvinceCity = localStorage.getItem("selectedProvince") + "-" + localStorage.getItem("selectedCity");
$('#provinceCity').append($('<option>', {
value: selectedProvinceCity,
text: selectedProvinceCity,
selected: "selected"
}));
setTimeout(function(){
$('#provinceCity').click(function(){
loadProvince();
$(this).unbind('click');
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
})
}, 500);
}
}
for (var i=0; i<province.length; i++){
if ($(this).val() == province[i]["id"]){
$("#provinceCity").empty();
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>");
}
}
}
});
$( window ).load(function() {
// Run code
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
});
});
Code wich replaces SELECT by DIVs runs only one time. When SELECT has changed later, it doesn't take effect.
You must run that code each time whan SELECT changed.
Just wrap code from w3school in function
Eg
And run convertSelect2Divs() at the end of functions loadProvince() and $("#provinceCity").change()