window.addEventListener('load', function() { var countryEl = $('#country-code'); var cityEl = $('#city-id'); var countryVal = countryEl.val(); if (countryVal == '') { cityEl.html(''); cityEl.prop('disabled', true); } else { cityEl.prop('disabled', false); } getCityFromCountryCodeAjax(countryVal, cityEl); countryEl.on('change', function() { var countryCode = $(this).val(); if (countryCode == '') { cityEl.prop('disabled', true); } else { cityEl.prop('disabled', false); } getCityFromCountryCodeAjax(countryCode, cityEl); }) ///////// FUNCTION ////////////////// function getCityFromCountryCodeAjax(countryCode, cityEl) { $.ajax({ type: "GET", url: "/geofence_area/getCityListDependOnCountryCodeAjax", data: { 'country_code' : countryCode }, cache: false, success: function(res) { res = JSON.parse(res); if (res.success) { var options = ''; var cityOldVal = cityEl.val(); var selected = ''; res.data.forEach(function(item, index) { if (cityOldVal == item.id) { selected = 'selected'; } else { selected = ''; } options += '' }); cityEl.html(options); } } }); } });