简体   繁体   中英

select2 - clear all items not working when targeting by class

I have a select2 combobox, from which I want to clear out all items.

If I target the select with an ID, then it works:

$("#clearId").click(function(){
  $("#list").empty();
});

However, if I target the select with a class, it actually removes the select from the dom:

$("#clearClass").click(function(){
    $(".list").empty();
});

This can be seen in the following demo: http://jsfiddle.net/NvrZu/

I need to be able to target the select via a class.

The dynamically added parent of the select also gets the .list class when the plugin wraps the original select, so you're not just removing the options in the select, but the select as well, as you're emptying the parent element.

Excluding the wrapper added by the plugin should solve that problem :

$("#clearClass").click(function(){
    $(".list").not('.select2-container').empty();
});

FIDDLE

                $("#list").empty();
                $("#list").select2('data', null);

http://jsfiddle.net/mohammadAdil/NvrZu/1/

$("#clearClass").click(function(){
     $("select.list").empty();
});

You do have other element with class .list that you don't want to empty

this is div generated by plugin with class list -

<div class="select2-container list"

See On console --> http://jsfiddle.net/mohammadAdil/NvrZu/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM