Short question: I have a list of countries, and a dropdown menu where people can select multiple countries. I have a map where each key of the map is a country name, and each value of the country is a city. I want to put in options the cities from the countries selected, dynamically.
How to do this ?
<script>
$: countries_chosen = []
$: cities_chosen = []
let countries = ["france", "spain", "germany"]
let cities = []
let all_cities = {
"france": ["paris", "bordeau"],
"spain": ["barcelona", "madrid"],
"germany": ["berlin", "frankfurt"]
}
$: console.log(countries_chosen)
$: console.log(cities_chosen)
</script>
<h1>
countries
</h1>
<label>
<select multiple bind:value={countries_chosen}>
{#each countries as country}
<option value={country}>
{country}
</option>
{/each}
</label>
<h1>
cities
</h1>
<label>
<select multiple bind:value={cities_chosen}>
{#each cities as city}
<option value={city}>
{city}
</option>
{/each}
</label>
REPL: https://svelte.dev/repl/61c93b05a2374d1197fb3a38e86b75a1?version=3.46.4
Thanks !
CodePudding user response:
You would reactively fill up the cities array based on countries_chosen
by simply mapping each of the selected countries to their respective cities and then flattening this array.
$: cities = countries_chosen.map(c => all_cities[c]).flat()
CodePudding user response:
here is the working code:
<script>
$: countries_chosen = []
$: cities_chosen = []
let countries = ["france", "spain", "germany"]
let cities = []
let all_cities = {
"france": ["paris", "bordeau"],
"spain": ["barcelona", "madrid"],
"germany": ["berlin", "frankfurt"]
}
$: console.log(countries_chosen)
$: console.log(cities_chosen)
</script>
<h1>
countries
</h1>
<label>
<select multiple bind:value={countries_chosen}>
{#each countries as country}
<option value={country}>
{country}
</option>
{/each}
</label>
<h1>
cities
</h1>
<label>
<select multiple bind:value={cities_chosen}>
{#each countries_chosen as country}
{#each all_cities[country] as city}
<option value={city}>
{city}
</option>
{/each}
{/each}
</label>