'How can I add a disabled option when populating a select with Vue.js v-for
I would like to add a disabled option to a select that I have bound with v-for binding. The Vue docs on select suggests adding one but the example is using hard coded options.
I want to create a disabled 'Please select one' with v-for binding to force the user to pick a option rather than defaulting to a particular selection. I currently add a 'Please select one' option to the list I'm binding the select to and it shows up and works fine but I don't want the user to be able to choose it again.
How can I accomplish this when using v-for binding to a select?
//Contrived example of adding the default selection text
data.dashboardDefinitionList.splice(0, 0, { Id: 0, Name:"Select a Dashboard" });
<select id="dashboardSelectNew" v-model="formVariables.dashboardDefIndex" v-on:change="getDashboard">
<option v-for="(dd, index) in dashboardDefinitionList"
:value="dd.Id"
:selected="formVariables.dashboardDefIndex == index">
{{ dd.Name }}
</option>
</select>
Solution 1:[1]
Put your disabled option first, then do the v-for.
<select id="dashboardSelectNew" v-model="formVariables.dashboardDefinition" @change="getDashboard">
<option disabled value="">Please select one</option>
<option v-for="dd in dashboardDefinitionList" :key="dd.id" :value="dd">
{{ dd.Name }}
</option>
</select>
Note that I've also attempted to clean up your model / value binding but you may not want or need it.
For the initial value, you would set it to an actual entry from your list instead of a specific index, eg
this.formVariables.dashboardDefinition = this.dashboardDefinitionList[someIndex]
Solution 2:[2]
You can use it like this adding disabled selected to appear first and cannot be selected also good practice to put value="0" because you are using id in the value attribute
<select id="dashboardSelectNew" v-model="formVariables.dashboardDefIndex" v-on:change="getDashboard">
<option value="0" disabled selected> Please select one </option>
<option v-for="(dd, index) in dashboardDefinitionList"
:value="dd.Id"
:selected="formVariables.dashboardDefIndex == index">
{{ dd.Name }}
</option>
</select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | abdelhak51 |
