In this tutorial, I’ll show you how to get selected option from a dropdown list in Vue.js.
Suppose you have a user settings form, which has a country field. And you want to get selected value and assign it to the data
component or perform some other actions.
Example using Vue.js
In Vue.js you can create your select options dynamically. Here we have a dynamic dropdown list of countries.
<select class="form-control" @change="changeCountry($event)">
<option value="" selected disabled>Choose</option>
<option v-for="country in countries" :value="country.code" :key="country.code">{{ country.name }}</option>
</select>
In Vue.js each option must have a :key
Our country field has a @change
event, which has a changeCountry
handler with
On every field changeCountry
changeCountry (event) {
this.user.address.country = event.target.value
console.log(event.target.value)
}
The advantages of using @change event instead of v-model binding
You might think how is it better than v-model
Full example
HTML
<div id="vue-instance">
<select class="form-control" @change="changeCountry($event)">
<option value="" selected disabled>Choose</option>
<option v-for="country in countries" :value="country.code" :key="country.code">{{ country.name }}</option>
</select>
<br><br>
<p><span>Selected country name: {{selectedCountry }}</span></p>
<p><span>User country: {{ user.address.country }}</span></p>
</div>
Vue.js
var vm = new Vue({
el: '#vue-instance',
data: {
countries: [
{ code: 'GB', name: 'Great Britain' },
{ code: 'US', name: 'United States' },
{ code: 'KZ', name: 'Kazakhstan' }
],
selectedCountry: null,
user: {
address: {
country: null
}
}
},
methods: {
changeCountry (event) {
this.user.address.country = event.target.value
this.selectedCountry = event.target.options[event.target.options.selectedIndex].text
}
}
});
https://jsfiddle.net/e3vqLmow/
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/get-selected-value-on-@change-in-vuejs
PS: Make sure you check other posts e.g. how to check if a user has scrolled to the bottom in Vue.js, how to do Vue.js polling using setInterval() and JavaScript/Vue.js print object in the console.
Incoming search terms:
Yes, this is nice.. but I have a doubt regarding this.. If we want to show the selected value in the dropdown, how should we assign the value to the dropdown? (We trigger the on-change method when we change the dropdown value. How to do vice-versa? i.e; assign the selected value to the dropdown)
You can assign
v-model="selected"
e.g.select v-model="selected"