1
votes

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

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.

Ive looked at $("#ddlinput").select2("val", "CA"); from the documenation, but this requires the item to be alreayd be bound to the 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.

3
You can make use of append() to add item in the select after clicking of button - lampdev
Thanks, to what element do I call append() on? Could you elaborate with an answer, I also want the element to be the selected one - DavidB
Are you binding select2 to a text input or a select element? - James Hafner
Im binding to a text input - DavidB

3 Answers

13
votes

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

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).

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
votes

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

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

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

});
0
votes

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

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