I have the following code for a select dropdown in html:
<select class="form-select" name="" id="" v-model="rp">
<option v-for="(educationGroup,index) in educationGroupList" :key="index" :value='educationGroup.id' :v-if="educationGroup.id == 2" selected>{{ educationGroup.name }}</option>
</select>
My problem is how can i set selected attribute in vue.js. IN my code "selected" code doesn't work.
You can make the selection with two options.
Option 1: Use v-model .
In this scenario, the value assigned for v-model
should match with the value
for option.
Example: In my example the value
for option
is assigned as educationGroup.id
where educationGroup
is individual objects in array educationGroupList
<select class="form-select" name="" id="" v-model="rp">
<option
v-for="(educationGroup,index) in educationGroupList"
:key="index"
:value='educationGroup.id'
:v-if="educationGroup.id == 2">
{{ educationGroup.name }}
</option>
</select>
Option 2: Use selected
attribute for option
.
Here selected
is an property that accepts dynamic value. So it should be prefixed with a :
and its value should be assigned with a condition on which the selection must be done. He in the below example :selected="educationGroup.id == 1"
. So the option with id
valie 1
will be selected.
<select class="form-select" name="" id="">
<option
v-for="(educationGroup,index) in educationGroupList"
:key="index"
:value='educationGroup.id'
:v-if="educationGroup.id == 2"
:selected="educationGroup.id == 1">
{{ educationGroup.name }}
</option>
</select>
Find the working example for both.
You can try calling an change event with @change
<select class="form-select" name="" id="" v-model="rp" @change="onChange()">
<option v-for="(educationGroup,index) in educationGroupList" :key="index" :value='educationGroup.id' :v-if="educationGroup.id == 2" selected>{{ educationGroup.name }}</option>
</select>
And then call onChange function in methods to get selected value as below:
export default {
methods: {
onChange: function() {
var options = event.target.options
if (options.selectedIndex > -1) {
var value= options[options.selectedIndex].getAttribute('value');
console.log(value)
}
}
},
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.