Reputation: 5107
I'm using html and laravel to build select box options in a foreach loop
This works and populates with ID as value and name as the option. What I want, and can't quite figure out here, is how to take my function when I call it and get the id and value as separate vue options for a post axios call I'm going to make.
So when I select the option and submit the form to call the function, how can I get the ID as one prop and the name as another?
<select>
@foreach($details as $detail)
<option value="{{$detail->id}}">{{$detail->name}}</option>
@endforeach
</select>
new Vue({
data: {
detailID: [''],
detailName: ['']
},
methods: {
let data = {
detailID: this.detailID,
detailName: this.detailName
};
}
})
Upvotes: 0
Views: 9102
Reputation: 214927
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>
Upvotes: 1
Reputation: 620
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
Upvotes: 2
Reputation: 290
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.
Upvotes: 0