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-multiselectfor the searchable dropdown:...and add some custom code to add the typed color to
listwhen Enter or Return is pressed:Note that you will have to add the CSS for vue-multiselect, which you can see how to do in the installation instructions here.
Sandbox & Full Code