Tuesday, February 16, 2016

Select2 dropdown with allow new values by user

I used the code below I am using Version: 3.4.5 of select2.

$('.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]'};
        }
    },
});

reference :
http://stackoverflow.com/questions/14577014/select2-dropdown-but-allow-new-values-by-user

No comments:

Post a Comment