jquery-select2

Select2 dropdown but allow new values by user?


I want to have a dropdown with a set of values but also allow the user to "select" a new value not listed there.

I see that select2 supports this if you are using it in tags mode, but is there a way to do it without using tags?


Solution

  • For version 4+ check this answer above by Kevin Brown

    In Select2 3.5.2 and below, you can use something like:

    $(selector).select2({
      minimumInputLength:1,
      "ajax": {
        data:function (term, page) {
          return { term:term, page:page };
        },
        dataType:"json",
        quietMillis:100,
        results: function (data, page) {
          return {results: data.results};
        },
        "url": url
      },
      id: function(object) {
        return object.text;
      },
      //Allow manually entered text in drop down.
      createSearchChoice:function(term, data) {
        if ( $(data).filter( function() {
          return this.text.localeCompare(term)===0;
        }).length===0) {
          return {id:term, text:term};
        }
      },
    });
    

    (taken from an answer on the select2 mailing list, but cannot find the link now)