Select2 dropdown but allow new values by user?

前端 未结 9 1461
灰色年华
灰色年华 2020-11-27 10:09

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

9条回答
  •  佛祖请我去吃肉
    2020-11-27 10:31

    For version 4+ check this answer below 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)

提交回复
热议问题