Reputation: 4701
I need to know the fastest way to remove hundreds of options from a dropdown list.
Right now, Firefox is really slow at updating my 2nd drop down dynamic list. Chrome is doing OK with the script but I need to speed up my removal of:
<select id="myDropDown" name="myDropDown">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
... all the way to let's say 500
</select>
Repopulating it is a breeze. I have a json parser that creates the
<option></option>
fields.
I've tried:
.remove()
.children().remove()
.empty()
They all have the same sluggish performance in removal of hundreds of options. Is there something I'm missing?
Upvotes: 2
Views: 2914
Reputation: 2941
The problem could be that jQuery attempts to cleanup when removing things, read .empty() for details (starting with "To avoid memory leaks...").
If you think that this isn't a problem in your situation, then
$("#someOption").text("");
may be the sledgehammer you need.
Upvotes: 0
Reputation: 18354
Interesting question. I think that if you want it to be really fast, you could just show/hide the options
$("#someOption").hide();
EDIT:
I think you may have an array of values that have to populate, let's say values
. It'd be fast if you traverse your options first and check for each one if it's in the values
array (not vice versa, would be slow). So having:
var values = [...]; //Array with values that must 'exist' in the dropdown
$("#select1 option").each(function(i, option){
option.style.display = ($.inArray(option.value, values) >= 0 ? 'block' : 'none');
});
Note that we're avoiding jquery selectors inside the loop to boost performance. We are not traversing the array first (and options inside) because searching in an array is much faster than searching an element (option in this case) with a specific attribute (value in this case) in the dom.
Hope this helps. Cheers
Upvotes: 0
Reputation: 24102
Have you tried looping through them?
$('#myDropDown option').each(function(i, option){ $(option).remove(); });
You can specify which ones by keeping track of the value of i
.
Upvotes: 1