Search code examples
vuejs2vue-multiselect

Vue MultiSelect -- how to let user add new name that doesn't exist in the data list?


I am using a "type and search" plugin called Vue-Multiselect to give the user the ability to search for a customer name in database. If the name exists in the database/drop-down list they can then select that name and it will auto populate the field(s).

However, if the name doesn't exist, how can I give the user the ability to type the new name into the field? Scenario: The user wants to add a new name that doesn't exist in the database Note: I do have an ApiService that I will POST to on form submission.

Here's my template code (also available in JSFIDDLE):

<multiselect 
    v-model="customer_last_name" 
    :options="options"
    placeholder="Select an existing customer or type to add a new one"
    :custom-label="customerSelectName"
    label="lastname"
    track-by="uid"
    :close-on-select="true" 
    :clear-on-select="false" 
    :hide-selected="true" 
    :preserve-search="true"  
    id="example"
    @select="onSelect"
  >
  </multiselect>

<!--           <label for="customer_first_name_input">First Name:</label><br>
          <input id="customer_first_name_input" type="text" v-model="customer_first_name" /> -->

Script:

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    customer_last_name: '',
    customer_first_name: '',
    options: [{"uid":"1","firstname":"John","lastname":"Doe","email":"[email protected]","phone":null,"c_organization":"ACME","c_title":null}, {"uid":"2","firstname":"Mary","lastname":"Smith","email":"[email protected]","phone":null,"c_organization":"NBA","c_title":"Miss"}]
    },
  methods: {
    customerSelectName (option) {
      return `${option.lastname}, ${option.firstname}`
    },
    onSelect (option, uid) {
        console.log(option, uid)
    }
  }
}).$mount('#app')

Solution

  • The vue-multiselect library allows this with the tags functionality.

    you need to add :taggable="true" @tag="addTag" :multiple="false"

    and add an addTag method:

    addTag (newTag) {
      const parts = newTag.split(', ');
    
      const tag = {
        uid: this.options.length + 1,
        firstname: parts.pop(),
        lastname: parts.pop()
      };
      this.options.push(tag);
      this.customer_last_name = tag;
    }
    

    This is just a sample method that would convert input Chavez, Martha into:

    {
      "uid": 3,
      "firstname": "Martha",
      "lastname": "Chavez"
    }
    

    You may want to update that function to better suit your needs

    jsfiddle: https://jsfiddle.net/dapo/nwvpd4m2/