How to clear a multiple select dropdown using jquery [duplicate]
Possible Duplicate:
Quick way to clear all selections on a multiselect enabled <select> with jQuery?
Dear All.
I have a problem. once i have a multiselect box and i want to clear all the contents of that when i clickon the reset button.
could you please provide me jquery for that?
Thanks.
Satya
I assume you mean clear selection:
//for jQuery >= 1.6
$('select option').removeProp('selected');
//for jQuery < 1.6
$('select option').removeAttr('selected');
To unselect all items if using jQuery 1.6.1 or later:
$('#mySelect').children().removeProp('selected');
or for backwards compatibilty:
$('#mySelect').children().removeAttr('selected');
For simplicity's sake I'm assuming that your HTML is well formed and that your select
only has option
children.
Also, if the list is large and performance is an issue, filter
the list so that you only change the ones that are actually selected - it's arguable whether it's simpler to simply deselect every option or only change the ones that need deselecting:
$('#mySelect').children(':selected').removeProp('selected');
[NB: using :selected
in the second function call is (according to the jQuery docs) more efficient than making a single compound selector]
In the future, you should post what you've tried so far - It gives people trying to answer your question a little more insight into what path you're taking, and where you might be going down the wrong path.
That being said, you can remove a list item from it's container with the .remove()
method, like this:
$('#list option').each(function(index, option) {
$(option).remove();
});
you can see it in action here: http://jsfiddle.net/y9pzS/
and here's a version that uses the .empty()
method to remove all of child items in the list: http://jsfiddle.net/y9pzS/1/
Note: there's a fair amount of ambiguity in your question. Not sure if you're looking to clear out the entire container, or just remove the selected items. This will remove all items from the select box.
See this SO post:
$("#my_select option:selected").removeAttr("selected");
精彩评论