Setting defaults in select2 using an AJAX call?

I have two examples.

This is one with regular select2 with static inputs, which works with default fields in advance: http://jsfiddle.net/z96Ca/2/

Next - select2 with ajax call, and the default values ​​are not added to the field - why ?! http://jsfiddle.net/z96Ca/1/

I have been playing the game for some time, but I can’t understand how to add values ​​in advance when there is an ajax call.

Here's a line that usually adds code in advance:

$(test).val(["test1","test2"]).trigger("change");

I hope I'm clear enough

Thank you so much

+4
source share
2 answers

Select2 , select, , , initSelection.

:

initSelection: function (element, callback) {
    callback($.map(element.val().split(','), function (id) {
        return { id: id, text: id };
    }));
}

jsfiddle


. :

$(test).val(["test1","test2"]).trigger("change");

:

$(test).select2('val', ["test1","test2"], true);

initSelection, :

: : val() , initSelection()


. , , (-ajax) initSelection, , tags.


: Select2 v4

Select2 v4 Select2 <select>, .

<select id="test" style="width: 300px;" multiple="multiple">
</select>

. multiple: true , multiple <select>.

, html <select>, , .

$test.append('<option value="initial1" selected="selected">initial1</option>');
$test.append('<option value="initial2" selected="selected">initial2</option>');
$test.trigger('change');

initSelection ( ).

jsfiddle

. Select2 , . .

+24

select2 initSelection.

+2

Source: https://habr.com/ru/post/1531670/


All Articles