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

时间:2022-11-27 18:40:56

I have a single selection select2 that uses an ajax search to find results. I have initialized it like this:

我有一个选择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
    })
}

What i would like to do is on a button click add a new item into the select via javascript.

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

Ive looked at $("#ddlinput").select2("val", "CA"); from the documenation, but this requires the item to be alreayd be bound to the select2.

我看过$(“#ddlinput”)。select2(“val”,“CA”);从文档中,但这要求项目被绑定到select2。

Any help would be great.

任何帮助都会很棒。


I think I may need to set the value of the input and recreate the select2, using initSelection function. I tried this and it doesn't work however. No errors, but nothing happens.

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

3 个解决方案

#1


12  

I'm using AJAX to bring provide suggestions that the user can click and add to the select box.

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

I went through a lot of pain with this, eventually I ended up with this (this is the suggestion click handler, i.e. the option text and value come from AJAX in the real world).

我经历了很多痛苦,最终我得到了这个(这是建议点击处理程序,即选项文本和值来自现实世界中的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');

Seems to do the trick.

似乎可以做到这一点。

#2


2  

You can make use of append() to add item in the select after clicking of button

您可以使用append()在单击按钮后在选择中添加项目

$('.submitClass').click(function(){

$('#selectId').append('<option selected="selected" value="val1">CA</option>');

});

#3


0  

Since the select2 is empty (since its remote data) I'm doing this: Clearing items, appending the value, selecting and triggering a change...

由于select2是空的(因为它的远程数据)我这样做:清除项目,附加值,选择和触发更改...

$(dd).empty().append('<option value="'+ selectedValue +'">'+ selectedValue +'</option>').val(selectedValue ).trigger('change');

#1


12  

I'm using AJAX to bring provide suggestions that the user can click and add to the select box.

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

I went through a lot of pain with this, eventually I ended up with this (this is the suggestion click handler, i.e. the option text and value come from AJAX in the real world).

我经历了很多痛苦,最终我得到了这个(这是建议点击处理程序,即选项文本和值来自现实世界中的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');

Seems to do the trick.

似乎可以做到这一点。

#2


2  

You can make use of append() to add item in the select after clicking of button

您可以使用append()在单击按钮后在选择中添加项目

$('.submitClass').click(function(){

$('#selectId').append('<option selected="selected" value="val1">CA</option>');

});

#3


0  

Since the select2 is empty (since its remote data) I'm doing this: Clearing items, appending the value, selecting and triggering a change...

由于select2是空的(因为它的远程数据)我这样做:清除项目,附加值,选择和触发更改...

$(dd).empty().append('<option value="'+ selectedValue +'">'+ selectedValue +'</option>').val(selectedValue ).trigger('change');