Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving text of select element

Tags:

vue.js

When binding a <select> element using vue.js's v-model, how would you get the selected option text as opposed to the selected option value?

In HTML:

<select v-model="selected" options="myOptions"></select>

In JS:

myOptions: [{ text: 'Blue', value: '1' }, { text: 'Green', value: '2' }]

What I would want to retrieve is both the text 'Blue' as well as the value '1' by doing something like {{ selected.text }} or {{ selected.value }}. However, you can only do {{ selected }} which returns the selected value by default.

Ref: Vue.js guide for Dynamic Select Options

like image 862
howellmartinez Avatar asked May 23 '15 09:05

howellmartinez


1 Answers

You can just use a filter, like this:

html:

<div id='vm'>
    Formatted value:<b> {{city | cityFormatter}} </b><br/>
    <br/>
    <select v-model="city" options="cities"></select>
</div>

js:

var vm = new Vue({
  el: '#vm',
  data: {
      city: 'city1',
      cities: [{text: 'Toronto', value: 'city1'}, 
               {text: 'Orleans', value: 'city2'}]
  },
  filters: {
      cityFormatter: function(val) {
          var newVal = '';
          this.cities.map(function(el){ 
              if (val == el.value){
                  newVal = el.value + ' ' + el.text;
              }
          });
          return newVal;
      }
  }
});

Working example: http://jsfiddle.net/qfy6s9Lj/9/

like image 199
swift Avatar answered Oct 12 '22 23:10

swift