Vue.js get selected option on @change
Use v-model
to bind the value of selected option's value. Here is an example.
<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
data: {
key: ""
},
methods: {
onChange(event) {
console.log(event.target.value)
}
}
}
</script>
More reference can been seen from here.
how to change selected value dynamically using vue?
Don't assign default values in created
!
That's what data
is for. Declaring each sub-property inside data
(with any value, other than undefined
) will allow Vue to wrap setters and getters around them, making them reactive.
Run changeSearchMonths
once inside mounted
so your custom logic is applied to the default values. I took the liberty to rewrite bits of your code to make it slightly more readable.
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
searchParams: {
searchToInvoiceDate: '06',
searchFromInvoiceDate: '01',
planConfirmFlag: 'P',
searchTaxTerm: '1'
}
}),
methods: {
pad(n) {
return `${n}`.padStart(2, '0')
},
changeSearchMonths() {
const p = this.searchParams;
switch (true) {
case p.searchTaxTerm === '1' && p.planConfirmFlag === 'P':
p.searchFromInvoiceDate = '01';
p.searchToInvoiceDate = '03';
break;
case p.searchTaxTerm === '1' && p.planConfirmFlag === 'F':
p.searchFromInvoiceDate = '04';
p.searchToInvoiceDate = '06';
break;
case p.searchTaxTerm === '2' && p.planConfirmFlag === 'P':
p.searchFromInvoiceDate = '07';
p.searchToInvoiceDate = '09';
break;
case p.searchTaxTerm === '2' && p.planConfirmFlag === 'F':
p.searchFromInvoiceDate = '10';
p.searchToInvoiceDate = '12';
break;
default:
}
}
},
mounted() {
this.changeSearchMonths()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<span class="selectboxWrap">
<select @change="changeSearchMonths" ref="comCd"
v-model="searchParams.searchTaxTerm">
<option value="1">1</option>
<option value="2">2</option>
</select>
</span>
<span class="selectboxWrap">
<select @change="changeSearchMonths" ref="comCd"
v-model="searchParams.planConfirmFlag">
<option value="P">P</option>
<option value="F">F</option>
</select>
</span>
<br>
<div class="boxHorizental">
<span class="dateRange full">
<div class="selectboxWrap">
<select v-model="searchParams.searchFromInvoiceDate">
<option v-for="n in 12" :key="n" :value="pad(n)" v-text="n" />
</select>
</div>
<em class="dash">~</em>
<div class="selectboxWrap">
<select v-model="searchParams.searchToInvoiceDate">
<option v-for="n in 12" :key="n" :value="pad(n)" v-text="n" />
</select>
</div>
</span>
</div>
</div>
Setting default dynamic value for <select> option in Vue js
You can bind :selected="tutor_work.start_year"
:
new Vue({
el: "#demo",
data() {
return {
tutor_work: {
organization: "ff",
start_year: "2010",
finish_year: "2019",
},
}
},
computed : {
years () {
const year = new Date().getFullYear()
return Array.from({length: year - 1980}, (value, index) => 1981 + index)
}
}
}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<select v-model="tutor_work.start_year">
<option v-for="year in years" :key="year" :value="year" :selected="tutor_work.start_year">{{ year }}</option>
</select>
</div>
VueJS Using @click on <option> elements and @change on <select> element
There's no need for the additional noSecurity
variable. Create your select with v-model
to track the selected value. Give each option a value
attribute.
<select v-model="selected">
<option value="">Please select a security type</option>
<option value="none">No Security</option>
<option value="personal">Personal</option>
<option value="enterprise">Enterprise</option>
</select>
Check that value:
<div v-if="selected === 'none'">something</div>
You can still use the noSecurity
check if you prefer by creating a computed:
computed: {
noSecurity() {
return this.selected === 'none';
}
}
Here's a demo showing both:
new Vue({
el: "#app",
data() {
return {
selected: ''
}
},
computed: {
noSecurity() {
return this.selected === 'none';
}
},
methods: {},
created() {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="selected">
<option value="">Please select a security type</option>
<option value="none">No Security</option>
<option value="personal">Personal</option>
<option value="enterprise">Enterprise</option>
</select>
<div v-if="selected === 'none'">something</div>
<div v-if="noSecurity">something</div>
</div>
How do I pass a data attribute in vue js select option
event.target refers to the SELECT not the options... you have to select the selected option and get it's attribute
event.target.options[event.target.options.selectedIndex].getAttribute('test')
here is the full component example
<template>
<div>
<select v-model="val" @change="updateTest($event)" style="width: 100px" test="Test">
<option v-for="programme in list" :key="programme.id" :value="programme.id" :test="programme.name">{{ programme.value }} )</option>
</select>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
val: null,
list: [
{id: 1, name: "John", value: "A"},
{id: 2, name: "Jack", value: "B"},
]
}
},
methods: {
updateTest(event) {
console.log(event.target.options[event.target.options.selectedIndex].getAttribute('test'))
}
}
}
</script>
<style scoped>
</style>
How to set default selected value in select with vue.js?
If you only want to set it as a default value, vou can use the :value
-Property and just pass the first Object from the answer-array that has selected set to true.
:value="question.answers[0].answer.find(answer -> answer.selected)"
Note that when using that the value is not bound to what is selected, so if you select a different item the data in the parent component will not update! If you want it automatically updated, you should consider using v-model along with computed-properties.
Edit:
Ok so I've looked into your question a bit deeper and I think I came up with a pretty good solution.
First of all, I don't really understand the properties you set in the v-select component, since none of them are defined in the VueSelect Api. In this answer I use the properties defined there. Also, I'm not quite sure how to interpret your data structure, so I'll just give an example with a array of questions which contains an id, a question text and an array of answers.
In order to use v-model with a computed property you have to to implement a getter which will be called to set the v-select-component data and a setter for updating the data when a different item is selected in the select-component. Since in your case you would have to have one computed property for each element in the questions-array, you should wrap the display of a question-object into its own component and display multiple of those in a loop.
Vue.component('v-select', VueSelect.VueSelect);Vue.component("question", { "template": "#questionTemplate", "props": { "question": Object }, "computed": { "selectedId": { "get": function() { return this.question.answers.find(answer => answer.selected).id; }, "set": function(id) { //set selected flag on newly selected element this.question.answers.find(answer => answer.id === id).selected = true; //reset previous choice this.question.answers.find(answer => answer.selected && answer.id !== id).selected = false; } } }});
new Vue({ "el": "#app", "data": function() { return { "questions": [ { "id": 83, "question": "QuestionText", "answers": [ { "answer": "Answer 1", "id": 216, "questionID": 83, "selected": false, "sortOrder": 1 }, { "answer": "Answer 2", "id": 217, "questionID": 83, "selected": true, "sortOrder": 2 } ] } ] } }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><script src="https://unpkg.com/vue-select@latest"></script><link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css">
<div id="app"> <question v-for="question in questions" :question="question" :key="question.id"></question></div>
<script type="text/x-template" id="questionTemplate"> <div> <p>{{question.question}}</p> <v-select v-model="selectedId" :options="question.answers" label="answer" :reduce="answer => answer.id"></v-select> <p>Selected AnswerId: {{selectedId}}</p> </div></script>
Related Topics
Angular 2 Concatenate Variable in Interpolation
What Does This Format Means T00:00:00.000Z
Check Whether an Input String Contains a Number in JavaScript
Remove Insignificant Trailing Zeros from a Number
How to Change Value of Object Which Is Inside an Array Using JavaScript or Jquery
Retaining the Textbox Values Even After Refresh
Why Does Google Chrome Always Add Space After Selected Text
How to Print Star Pattern in JavaScript in a Very Simple Manner
Click on Pseudo Element Using Selenium
How to Insert Dashes Between Each Two Even Digits of a Specific Number
Get Directory of a File Name in JavaScript
Regex: Match a Word With Exactly One Occurrence of a Specified Character At the Beginning
Retrieving Keys from Json Array Key-Value Pair Dynamically - JavaScript
How to Reload a Page With React-Router