1

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.

1

2 Answers 2

1

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)
      }
    }
  },
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

https://codepen.io/devkr/pen/poPRdWm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.