How to set selected value of jquery select2?

后端 未结 28 1471
野趣味
野趣味 2020-11-30 00:00

This belong to codes prior to select2 version 4

I have a simple code of select2 that get data from ajax



        
28条回答
  •  余生分开走
    2020-11-30 01:01

    You should use:

    var autocompleteIds= $("#EventId");
    autocompleteIds.empty().append('').val("Id").trigger('change');
    
    // For set multi selected values
    var data =  [];//Array Ids
    var option =  [];//Array options of Ids above
    autocompleteIds.empty().append(option).val(data).trigger('change');
    
    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR) {
        // append the new option
        $("#EventId").append('');
    
        // get a list of selected values if any - or create an empty array
        var selectedValues = $("#EventId").val();
        if (selectedValues == null) {
            selectedValues = new Array();
        }
        selectedValues.push(response.id);   // add the newly created option to the list of selected items
        $("#EventId").val(selectedValues).trigger('change');   // have select2 do it's thing
    });
    

提交回复
热议问题