Select2 dropdown but allow new values by user?

前端 未结 9 1465
灰色年华
灰色年华 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: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 = ;
    $('.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]'};
            }
        },
    });
    

提交回复
热议问题