I have two custom select input fields in a form: Country and City. City is depended on the Country, as you may have already guessed. So when a user selects a country:
- an ajax call is performed
- the cities of that selected country are fetched
- fetched cities are displayed in the second selectbox
Scenario: From the country selectbox, I selected United States. From the city selectbox I selected Texas (which has the value: 6). Now if I go back to the first select box and change the country to United Kingdom, it will automatically select the 6th city of UK based on the previous selection.
Here is what I am doing:
<custom-select type="select" name="country_id" @change="selectCountry"> <option disabled selected>Choose a Country</option> <option v-for="country in countries" :value="country.id">@{{ country.name }}</option> </custom-select> <custom-select type="select" name="city_id" @change="selectCity"> <option disabled selected>Choose a City</option> <option v-for="city in cities" :value="city.id">@{{ city.name }}</option> </custom-select>
How do I reset the city selection everytime I select a country?
Advertisement
Answer
The thing is that Vue tries to reuse existing HTML in order to speed up rendering. In your case it chooses not to rerender HTML for select boxes, and it just changes text content of options. Simple way to say force rerendering is to use different key prop for city select depending on selected country:
<custom-select type="select" :key="selectedCountryId" name="city_id" @change="selectCity"> <option disabled selected>Choose a City</option> <option v-for="city in cities" :value="city.id">@{{ city.name }}</option> </custom-select>
Note, I added :key="selectedCountryId"
to the city select. You will need to create this selectedCountryId
property in selectCountry
method, for example:
selectCountry (e) { this.selectedCountryId = e.target.selectedIndex axios.get(...) }