Clear dropdown using jQuery Select2

前端 未结 15 1932
情深已故
情深已故 2020-11-28 11:35

I\'m trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 qu

相关标签:
15条回答
  • 2020-11-28 12:24

    For select2 version 4 easily use this:

    $('#remote').empty();
    

    After populating select element with ajax call, you may need this line of code in the success section to update the content:

      success: function(data, textStatus, jqXHR){
      $('#remote').change();
                    } 
    
    0 讨论(0)
  • 2020-11-28 12:26

    This works for me:

     $remote.select2('data', {id: null, text: null})
    

    It also works with jQuery validate when you clear it that way.

    -- edit 2013-04-09

    At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

    $remote.select2('data', null)
    
    0 讨论(0)
  • 2020-11-28 12:26

    From >4.0 in order to really clean the select2 you need to do the following:

    $remote.select2.val('');
    $remote.select2.html('');
    selectedValues = []; // if you have some variable where you store the values
    $remote.select2.trigger("change");
    

    Please note that we select the select2 based on the initial question. In your case most probably you will select the select2 in a different way.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题