How to set selected value of jquery select2?

后端 未结 28 1133
野趣味
野趣味 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 00:57

    I did something like this to preset elements in select2 ajax dropdown

          //preset element values
            $(id).val(topics);
           //topics is an array of format [{"id":"","text":""}, .....]
              setTimeout(function(){
               ajaxTopicDropdown(id,
                    2,location.origin+"/api for gettings topics/",
                    "Pick a topic", true, 5);                      
                },1);
            // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url
    
    0 讨论(0)
  • 2020-11-30 01:00

    In Select2 V.4

    use $('selector').select2().val(value_to_select).trigger('change');

    I think it should work

    0 讨论(0)
  • 2020-11-30 01:01

    Set the value and trigger the change event immediately.

    $('#selectteam').val([183,182]).trigger('change');
    
    0 讨论(0)
  • 2020-11-30 01:01

    You should use:

    var autocompleteIds= $("#EventId");
    autocompleteIds.empty().append('<option value="Id">Text</option>').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('<option value="' + response.id + '">' + response.text + '</option>');
    
        // 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
    });
    
    0 讨论(0)
提交回复
热议问题