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
3 Answers
Reset to default 5The 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/