Select2 dropdown but allow new values by user?

前端 未结 9 1388
灰色年华
灰色年华 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:19

    The excellent answer provided by @fmpwizard works for Select2 3.5.2 and below, but it will not work in 4.0.0.

    Since very early on (but perhaps not as early as this question), Select2 has supported "tagging": where users can add in their own value if you allow them to. This can be enabled through the tags option, and you can play around with an example in the documentation.

    $("select").select2({
      tags: true
    });
    

    By default, this will create an option that has the same text as the search term that they have entered. You can modify the object that is used if you are looking to mark it in a special way, or create the object remotely once it is selected.

    $("select").select2({
      tags: true,
      createTag: function (params) {
        return {
          id: params.term,
          text: params.term,
          newOption: true
        }
      }
    });
    

    In addition to serving as an easy to spot flag on the object passed in through the select2:select event, the extra property also allows you to render the option slightly differently in the result. So if you wanted to visually signal the fact that it is a new option by putting "(new)" next to it, you could do something like this.

    $("select").select2({
      tags: true,
      createTag: function (params) {
        return {
          id: params.term,
          text: params.term,
          newOption: true
        }
      },
      templateResult: function (data) {
        var $result = $("<span></span>");
    
        $result.text(data.text);
    
        if (data.newOption) {
          $result.append(" <em>(new)</em>");
        }
    
        return $result;
      }
    });
    
    0 讨论(0)
  • 2020-11-27 10:20

    Since many of these answers don't work in 4.0+, if you are using ajax, you could have the server add the new value as an option. So it would work like this:

    1. User searches for value (which makes ajax request to server)
    2. If value found great, return the option. If not just have the server append that option like this: [{"text":" my NEW option)","id":"0"}]
    3. When the form is submitted just check to see if that option is in the db and if not create it before saving.
    0 讨论(0)
  • 2020-11-27 10:24

    Just for the sake of keep the code alive, I'm posting @rrauenza Fiddle's code from his comment.

    HTML

    <input type='hidden' id='tags' style='width:300px'/>
    

    jQuery

    $("#tags").select2({
        createSearchChoice:function(term, data) { 
            if ($(data).filter(function() { 
                return this.text.localeCompare(term)===0; 
            }).length===0) 
            {return {id:term, text:term};} 
        },
        multiple: false,
        data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
    });
    
    0 讨论(0)
  • 2020-11-27 10:25

    Thanks for the help guys, I used the code below within Codeigniter I I am using version: 3.5.2 of select2.

    var results = [];
    var location_url = <?php echo json_encode(site_url('job/location')); ?>;
    $('.location_select').select2({
        ajax: {
            url: location_url,
            dataType: 'json',
            quietMillis: 100,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                results = [];
                $.each(data, function(index, item){
                    results.push({
                        id: item.location_id,
                        text: item.location_name
                    });
                });
                return {
                    results: results
                };
            }
        },
        //Allow manually entered text in drop down.
        createSearchChoice:function(term, results) {
            if ($(results).filter( function() {
                return term.localeCompare(this.text)===0; 
            }).length===0) {
                return {id:term, text:term + ' [New]'};
            }
        },
    });
    
    0 讨论(0)
  • 2020-11-27 10:26
    var text = 'New York Mills';
    var term = 'new york mills';
    return text.localeCompare(term)===0;
    

    In most cases we need to compare values with insensitive register. And this code will return false, which will lead to the creation of duplicate records in the database. Moreover String.prototype.localeCompare () is not supported by browser Safary and this code will not work in this browser;

    return this.text.localeCompare(term)===0;
    

    will better replace to

    return this.text.toLowerCase() === term.toLowerCase();
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题