Luiz Wynne
Luiz Wynne

Reputation: 500

Vue.js set selected value on option with conditional not working

I am trying to set a selected value for an object option inside a select if this ID matched another object. I have a Company sectors array of objects that come from an API and a company that has a sector, coming from another API call. This way, if the sector_id field coming from the Company's API call matched the ID of the Array of sectors coming from another API, then this item should have the select "check". For some reason the way i am doing is not working. Does someone know why?

This is my code:

<select v-model="company.descripion" name="role">
                        <option v-for="company_sector in this.company_sectors" :key="company_sector.id" :company_sector.id="company_sector" 
                        v-bind:select="company_sector.id == company.sector_id">
                            {{company_sector.name}}
                        </option>
                </select> 

This for example, a piece of what comes from the Company API. No problem with that, the Json returned works fine:

 "company": {
    "id": 8,
    "sector_id": 19,
    "sector": {
      "id": 19,
      "name": "Consultancy/ Services"
    },

and this is a piece of what comes from the company_sectors API, also working great

[
  {
    "id": 19,
    "name": "Consulting"
  },
...then many other elements...
]

Instead of displaying the Consulting name as the option selected on the list, the first element of the company_sectors list if displayed as selected, as by default.

Any ideas on . what is going on?

Upvotes: 0

Views: 2018

Answers (1)

Lana
Lana

Reputation: 1267

1) For choosing an option programmatically use v-model for select element.

2) Set value attribute of each option to company_sector.id. So, you will get id of chosen option in your v-model variable and you will be able to choose the option programmatically by id.

The working code snippet is below:

var vm = new Vue({
  el: '#app',
  data: {
    selected: null,
    company: {
      id: 8,
      sector_id: 19,
      sector: {
        id: 19,
        name: "Consultancy/ Services"
      }
    },
    company_sectors: [
      {
        id: 19,
        name: "Consulting 19"
      },
      {
        id: 20,
        name: "Consulting 20"
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <select v-model="selected" name="role">
    <option v-for="company_sector in company_sectors" :key="company_sector.id" :value="company_sector.id">
    {{company_sector.name}}
  </option>
 </select> 
 <button @click="selected = company.sector_id">Set value</button>
</div>

Upvotes: 1

Related Questions