How can I add an input box into a select
element, with Vue?
Let's say I've got a list like ['Red', 'Yellow', 'Green']
, and the user wants to choose 'Black' which not in the list.
I want the user to be able to type it, within the select element, get it added to the list, and be selected.
Here is my code so far:
<template>
<div >
<div class="form-group col-md-2">
<label >Colors</label>
<select v-model="selected" class="form-control" >
<option v-for="option in list" class="form-control" :key="option">
{{ option}}
</option>
</select>
</div>
<p>The selected color is: {{selected}}</p>
</div>
</template>
<script>
export default {
data(){
return{
list:['Red', 'Yellow', 'Green'],
selected: '',
};
},
}
</script>
You can use vue-multiselect
for the searchable dropdown:
<multiselect
:options="list"
v-model="selected"
></multiselect>
...and add some custom code to add the typed color to list
when Enter or Return is pressed:
<div @keyup.enter="addColor($event)">
<multiselect
:options="list"
v-model="selected"
@search-change="typed = $event"
></multiselect>
</div>
addColor() {
if (!this.list.includes(this.typed)) this.list.push(this.typed); // check if inputted color is already in the list; if not, add it; if so, don't
this.selected = this.typed; // set `selected` to the currently typed color
},
Note that you will have to add the CSS for vue-multiselect, which you can see how to do in the installation instructions here.