以编程方式将所选选项添加到Select2中

Dav*_*idB 1 jquery jquery-select2

我有一个选择select2使用ajax搜索来查找结果.我已经像这样初始化它:

Task.ConfigureAssignee = function (objId) {

    var sectionID = (Utilities.GetQueryStringParams('subsection') != undefined) ? Utilities.GetQueryStringParams('subsection') : "-1";

    $(objId).select2({
        placeholder: 'Type names of people...',
        minimumInputLength: 3,
        multiple: false,
        width: '520px',
        id: function (obj) {
            return obj.ID;
        },
        ajax: { 
            type: "POST",
            datatype: 'json',
            url: "/webservices/globalwebservice.asmx/EventInviteSearch",
            data: function (term) {
                return JSON.stringify({ q: term, sectionId: sectionID });
            },
            contentType: 'application/json; charset=utf-8',
            results: function (data, page) { 
                return { results: data.d.SearchResults };
            }
        },
        formatResult: Task.FormatPersonSearchResult,
        formatSelection: Task.PersonForSelection
    })
}
Run Code Online (Sandbox Code Playgroud)

我想做的是点击一下按钮,通过javascript将一个新项目添加到选择中.

$("#ddlinput").select2("val", "CA");从文档中看了一下,但是这需要将项目绑定到select2.

任何帮助都会很棒.


我想我可能需要设置输入的值并使用initSelection函数重新创建select2.我试过这个,然而它不起作用.没有错误,但没有任何反应.

Ami*_*ber 12

我正在使用AJAX提供用户可以单击并添加到选择框的建议.

我经历了很多痛苦,最终我得到了这个(这是建议点击处理程序,即选项文本和值来自现实世界中的AJAX).

var select = $('#myselect');
var option = $('<option></option>').
     attr('selected', true).
     text("An Option").
     val(42);
/* insert the option (which is already 'selected'!) into the select */
option.appendTo(select);
/* Let select2 do whatever it likes with this */
select.trigger('change');
Run Code Online (Sandbox Code Playgroud)

似乎可以做到这一点.