JSFiddle - React, Tailwind, and code Playground
HTML
Countries <select id='TravelToCountryId'></select>
<br/>
Cities <select id='TravelToCityId'></select>
JavaScript
$(function() {
// Models
var countries =
[
{
CountryId: 1, CountryName: 'Philippines',
Cities :
[
{ CityId: 1, CityName: 'Manila' },
{ CityId: 2, CityName: 'Makati' },
{ CityId: 3, CityName: 'Quezon' },
]
},
{
CountryId: 2, CountryName: 'Canada',
Cities:
[
{ CityId: 4, CityName: 'Toronto' },
{ CityId: 5, CityName: 'Alberta' },
{ CityId: 6, CityName: 'Winniepeg' },
]
},
{
CountryId: 3, CountryName: 'China',
Cities:
[
{ CityId: 7, CityName: 'Beijing' },
{ CityId: 8, CityName: 'Shanghai' }
]
},
];
// Controller that live two lives,
// can't focus well on model :-)
// Populate then wire event...
var country = $('#TravelToCountryId');
var city = $('#TravelToCityId');
$.each(countries, function() {
var option = $('<option />').val(this.CountryId).text(this.CountryName);
country.append(option);
});
$(country).change(function() {
filterCitiesByCountry();
});
// ...Populate then wire event
// Init..
var initialCountryId = countries[1].CountryId;
$(country).val(initialCountryId);
filterCitiesByCountry();
// ...Init
function filterCitiesByCountry() {
var selectedCountryId = country.val();
// filter works on all browsers, except <= IE8
var countryObj = countries.filter(function(v) {
return v.CountryId == selectedCountryId;
})[0];
var cities = countryObj.Cities;
city.empty();
...