JSFiddle - React, Tailwind, and code Playground

by Avi Algaly

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<select id="ddlCountries" class="ddl-countries"></select>
<select id="ddlCities" class="ddl-cities"></select>

CSS

.ddl-countries {
    color:red;
}

JavaScript

var countries = [{
    "id": 1,
        "name": "ישראל"
}, {
    "id": 2,
        "name": "United States"
}];
var citiesByCountry = [{
    "countryId": 1,
        "id": 2,
        "cityName": "ירושלים"
}, {
    "countryId": 1,
        "id": 1,
        "cityName": "תל אביב"
}, {
    "countryId": 2,
        "id": 4,
        "cityName": "Boston"
}, {
    "countryId": 2,
        "id": 5,
        "cityName": "Chicago"
}, {
    "countryId": 2,
        "id": 3,
        "cityName": "New York"
}, {
    "countryId": 2,
        "id": 6,
        "cityName": "Ohayo"
}];

var geoModel = {
    getCitiesByCountryId: function (countryId) {
        if (!_.isNumber(countryId)) {
            return [];
        }
        return _.filter(citiesByCountry, function (city) {
            return city.countryId === countryId;
        });
    }
};

var geoView = {
    countryDDL: $("#ddlCountries"),
    cityDDL: $("#ddlCities"),
    populateCountries: function () {
        this.countryDDL.html("");
        _.each(countries, function (country) {
            this.countryDDL.append('<option value="' + country.id + '">' + country.name + '</option>');
        }, this);
    },
    populateCities: function () {
        var countryId, cities;
        this.cityDDL.html("");
        countryId = parseInt(this.countryDDL.val(), 10);
        cities = geoModel.getCitiesByCountryId(countryId);
        _.each(cities, function (city) {
            this.cityDDL.append('<option value="' + city.id + '">' + city.cityName + '</option>');
        }, this);
    },
    init: function () {
        this.countryDDL.off("change");
        this.populateCountries();
        var _this = this;
        this.countryDDL.on("change", function () {
            _this.populateCities.call(_this);
        });
        //this.countryDDL.trigger("change");
    }
};

geoView.init();

/*
$(countries).each(function () {
    var option = $('<option />');
    option.attr('id', this.id).text(this.name);
   ...