[Vuejs]-Get Select option text with VueJs

2👍

Client-side rendered select options

Since your values happen to be zero-based numbers (0 through 5), you could keep the translation keys in an array in the component:

JS:

data: {
    ageCategory: 0,
    ageValues: [
        'core.no_age',
        'core.children',
        'core.teenagers',
        'core.adults',
        'core.masters',
        'core.custom'
    ],
},
methods: {
    calculateCategoryName: function(event) {
        var ageCategory = this.ageCategory;
        var ageCategoryName = this.ageValues[this.ageCategory];
    }
}

Then you can render out those values using a v-for loop:

<select v-model="ageCategory" class="form-control" @change="calculateCategoryName">
    <option v-for="ageValue in ageValues" :value="$index">{{ trans(ageValue) }}</option>
</select>

Server-side rendered select options

If you need to get the value out of the actual select option, you can just get it through the DOM, using v-el:

methods: {
    calculateCategoryName: function() {
        var ageCategory = this.ageCategory;
        var $ageCategorySelect = this.$els.ageCategory;
        var ageCategoryOption = $ageCategorySelect.options[$ageCategorySelect.selectedIndex];
        var ageCategoryName = ageCategoryOption.text;
    }
}

HTML:

<select v-model="ageCategory" class="form-control" @change="calculateCategoryName" v-el:age-category>
    <option value="0">{{trans('core.no_age')}}</option>
    <option value="1">{{trans('core.children')}}</option>
    <option value="2">{{trans('core.teenagers')}}</option>
    <option value="3">{{trans('core.adults')}}</option>
    <option value="4">{{trans('core.masters')}}</option>
    <option value="5">{{trans('core.custom')}}</option>
</select>
👤nils

Leave a comment