最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - select2 - clear all items not working when targeting by class - Stack Overflow

programmeradmin1浏览0评论

I have a select2 bobox, 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: /

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

I have a select2 bobox, 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/NvrZu/

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

Share Improve this question asked May 9, 2013 at 16:26 JonoBJonoB 5,91717 gold badges59 silver badges77 bronze badges 1
  • @PalashMondal Look at the fiddle... – Ian Commented May 9, 2013 at 16:33
Add a ment  | 

3 Answers 3

Reset to default 5

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/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/mohammadAdil/NvrZu/4/

发布评论

评论列表(0)

  1. 暂无评论