'How to get index of selected option with vue.js
Sorry for newbie question. But how can i get an index of selected element from selectbox and run a function. My code below doesn't trigger switchView() function.
<select id="selectbox" @change="switchView(index)">
<option [v-for="(item, index) in items" v-bind:value="item.title"]>
{{ item.title }}
</option>
</select>
any help will be appreciated.
EDITED:
moved @change="switchView(index)" from <option> to <select>, thanks to @Phil
I need index, because i have several calculated items. And i need change view according to user's selection from items.
Solution 1:[1]
Pass $event.target.selectedIndex to your function
Use the @change directive to listen to the change event. Invoke your function and pass the $event or the selected index of the event target $event.target.selectedIndex as a parameter to your function.
<select @change="switchView($event, $event.target.selectedIndex)">
Your method receives the passed parameters.
methods: {
switchView: function(event, selectedIndex) {
console.log(event, selectedIndex);
}
}
Full Example https://jsfiddle.net/3p7rhjyw/
<div id="app">
<select @change="switchView($event, $event.target.selectedIndex)">
<option v-for="(item, index) in items" v-bind:value="item.title">
{{ item.title }}
</option>
</select>
<p>
{{ selectedIndex }} {{ items[selectedIndex].id }}
</p>
</div>
<script>
new Vue({
el: "#app",
data: {
items: [
{ title: "Learn JavaScript", id: 'A' },
{ title: "Learn Vue", id: 'B' },
{ title: "Play around in JSFiddle", id: 'C' },
{ title: "Build something awesome", id: 'D' }
],
selectedIndex: 0
},
methods: {
switchView: function(event, selectedIndex) {
console.log(event, selectedIndex);
this.selectedIndex = selectedIndex;
}
}
});
</script>
Mozilla documentation about HTMLSelectElement.selectedIndex.
Solution 2:[2]
For an pre-modified bootstrap-vue, this event handling might be different from the $event.target.selectedIndex. Especially for Vue 3, this answer might save your time.
<b-form-select @change="onChange" :options="options"></b-form-select>
Method that receives event from the user selection.
methods: {
onChange: function(event) {
let index = event.target.selectedIndex
}
}
Full Example might be as follows:
<div id="app">
<select @change="onChange">
</select>
<p>Selected index: {{ selectedIndex }}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
items: [
"option 1",
"option 2",
"option 3",
"option 4"
],
selectedIndex: 0
},
methods: {
onChange: function(event) {
let index = event.target.selectedIndex // this selectedIndex is from event.
this.selectedIndex = index
}
}
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | zemunkh |
