Question

I want select2 to behave as sort of combobox.See attached image for ref. So if user types in a string but it is not found in source array, then on enter or closing select2 it should add that new string to source. So say if there were 2 values before, after above there would be now 3.

select2 just like combobox in file open dialogs

enter image description here

I have created sample code, but cant make it to work.I am unable to update source.

JSFIDDLE:

HTML:

<div class="row">
    <div class="col-md-2">
        <input type="hidden" id="select2_sample3" class="form-control ">
    </div>
</div>

JS:

$(function () {

    var preload_data = {
        results: [{
            id: 'user0',
            text: 'Disabled User',
        }, {
            id: 'user1',
            text: 'Jane Doe'
        }]
    };

    $("#select2_sample3").select2({
        placeholder: "Select...",
        allowClear: true,
        minimumInputLength: 1,
        data: preload_data,
        query: function (query) {
            var data = {
                results: []
            }, i, j, s;
            for (i = 1; i < 5; i++) {
                s = "";
                for (j = 0; j < i; j++) {
                    s = s + query.term;
                }
                data.results.push({
                    id: query.term + i,
                    text: s
                });
            }
            query.callback(data);
        }

    }).on("select2-close", function () {
        // add to 
        console.log("close");
    });
});
Was it helpful?

Solution

I've recently had the same task. This is my solution:

<input type="hidden" name="trBrand" id="trBrand" class="form-control"></input>

and js code

$('#trBrand').select2({
    placeholder: 'choose something',
    allowClear: true,
    id: function(object) {
        return object.text;
    },
    createSearchChoice:function(term, data) {
        if ( $(data).filter( function() {
            return this.text.localeCompare(term)===0;
        }).length===0) {
            return {id:term, text:term};
        }
    },
    data:preload_data
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top