Как добавить значения jquery select2 с помощью initSelection

Вот мой множественный выбор select2 с ajax.

Первоначально я устанавливаю некоторые значения в initselection, как это

initSelection : function (element, callback) {
    var data = {id: 4, zipcode: "00602"};
    callback(data);
};

И затем я делаю выбор ajax.

Но я не могу поддерживать старые ценности. т. е. когда я ввожу новый выбор, старые значения заменяются вместо добавления .

Вот весь мой код.

var $select = $('#firstList');
$select.select2({
    placeholder : "Enter Pincode",
    allowClear : true,
    cache : true,
    initSelection : function(element, callback) {
        var data = {
            id : 4,
            zipcode : "00602"
        };
        callback(data);
    },
    ajax : {
        url : "../getZipList",
        type : "POST",
        contentType : "application/json; charset=utf-8",
        delay : 250,
        data : function(params) {
            //console.log(params)
            return {
                q : params.term, // search term
                page : params.page
            };
        },
        processResults : function(data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
            return {
                results : data.items
            };
            //console.log(data.it)
        },
        cache : true
    },
    escapeMarkup : function(markup) {
        return markup;
    }, // let our custom formatter work
    minimumInputLength : 1,
    templateResult : formatRepo, // omitted for brevity, see the source of this page
    templateSelection : formatRepoSelection // omitted for brevity, see the source of this page
});

Я использую версию select2 4.

Вот форматрепо

function formatRepo(repo) {
    if (repo.loading)
        return repo.text;
    var markup = '<div class="clearfix">' + '<div clas="col-sm-10">' + '<div class="clearfix">' + '<div class="col-sm-6">' + repo.zipcode + '</div>' + '</div>';

    markup += '</div></div>';
    return markup;
}

function formatRepoSelection(repo) {
    console.log(repo);
    return repo.zipcode;
    var cur_val = $('#zipcodeCollection').val();
    console.log(repo.zipcode);
    if (cur_val) {

        $('#zipcodeCollection').val(cur_val + "," + repo.zipcode);
    } else {

        $('#zipcodeCollection').val(repo.zipcode);
    }
    return repo.zipcode;

}

Что мне делать, чтобы сохранить старые значения и добавить их к новым значениям.


person SA__    schedule 27.05.2016    source источник


Ответы (1)


В методе processResults вам нужно добавить свои исходные данные в return:

data.items[data.items.length] = initialdata; results: data.items

initialdata должен находиться в глобальной/объектной области.

person faster    schedule 27.05.2016