Dependent Selects

Second selection filters based on first, using computed properties.

Live Demo

Select a country first.

Selected:

Source

HTML + JavaScript
<div data-component="dependent-selects">
    <select data-model="selectedCountry" data-action="change:resetCity">
        <option value="">Select country...</option>
        <option value="us">United States</option>
        <option value="uk">United Kingdom</option>
    </select>

    <!-- Cities filtered by country, rendered as a list -->
    <div data-show="selectedCountry" data-list="filteredCities">
        <template>
            <label>
                <input type="radio" name="city" data-action="pickCity">
                <span data-bind="label"></span>
            </label>
        </template>
    </div>
</div>

<script>
wildflower.component('dependent-selects', {
    state: {
        selectedCountry: '',
        selectedCity: '',
        cities: [
            { name: 'nyc', label: 'New York', country: 'us' },
            { name: 'la', label: 'Los Angeles', country: 'us' },
            { name: 'chi', label: 'Chicago', country: 'us' },
            { name: 'lon', label: 'London', country: 'uk' },
            { name: 'man', label: 'Manchester', country: 'uk' },
            { name: 'tok', label: 'Tokyo', country: 'jp' },
            { name: 'osa', label: 'Osaka', country: 'jp' }
        ]
    },
    computed: {
        filteredCities() {
            return this.cities.filter(c => c.country === this.selectedCountry);
        },
        selectionLabel() {
            const city = this.cities.find(c => c.name === this.selectedCity);
            return city ? city.label : '';
        }
    },
    resetCity() { this.selectedCity = ''; },
    pickCity(e, el, { index }) {
        this.selectedCity = this.filteredCities[index].name;
    }
});
</script>

Key Points

  • data-list="filteredCities" renders a computed array. The list re-renders automatically when the country changes
  • data-action="change:resetCity" on the first select clears the city when the country changes
  • City options are rendered with data-list as radio buttons, avoiding the limitation of dynamic <option> elements
  • The selectionLabel computed looks up the city name for display. Computed-to-computed dependency is automatic