How to get selected value on @change using Vue.js

in Code Write a comment

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 unique :key attribute. We’re using country codes as unique keys, e.g. GB, US or whatever format you prefer.

Our country field has a @change event, which has a changeCountry handler with an $event parameter.

On every field change changeCountry method is called. As you can see below, we simply assign the selected option to the user country field.

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 using v-model binding. The difference is that you can check user form for errors, assign it to multiple data components without using Vue.js watchers and so on.

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/[email protected]

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:

Write a Comment

Comment