[Vuejs]-Vue, get value and name of select option

1๐Ÿ‘

โœ…

Use v-model to bind the selection to your component data. SeeForm input bindings:

new Vue({
   data: {
      detailID: ""
   },
   // now you can access the id with this.detailID in your post request
})
<select v-model="detailID">
  @foreach($details as $detail)    
  <option value="{{$detail->id}}">{{$detail->name}}</option>
  @endforeach
</select>

And if you need both id and name, one work around could be:

new Vue({
   data: {
      detail: ""
   },
   // now you can access the id & name with this.detail.split(',') in your post request
})
<select v-model="detail">
  @foreach($details as $detail)    
  <option value="{{$detail->id.','.$detail->name}}">{{$detail->name}}</option>
  @endforeach
</select>
๐Ÿ‘คPsidom

2๐Ÿ‘

Here is a code example just using vue.js

Template

<div id="app">
  <select v-model="selectedDetailId">
    <option v-for="detail in details" v-bind:value="detail.id">
      {{ detail.name }}
    </option>
  </select>
</div>

Script

new Vue({
  el: '#app',
  data: {
    selectedDetailId: null,
    details: [
      { id: 1, name: 'A' },
      { id: 2, name: 'B' },
      { id: 3, name: 'C' }
    ]
  },
  methods:{
    post(){
       //your selected Id is this.selectedDetailId
    }
  }
})

You can find more details and examples in the official Vue.js docs.
https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings

๐Ÿ‘คVinicius Santin

0๐Ÿ‘

You would need to set a v-model to your select element and bind the entire object to each option element instead of just the id like you are doing in your example.
Here is a codepen with a simple example.

๐Ÿ‘คDavid Porcel

Leave a comment