views:

153

answers:

2

Hey all,

I'm attempting to repopulate a drop down menu. I'm making an ajax call to retrieve myList. When I have the new list, I remove all the options from the select element and insert the new values (about 100 options). This works great on later versions of IE and Firefox; the refresh is almost instant. However, on IE6, these operations really slow the browser down. The dropdown box almost becomes animated as options are removed from it, and this goes on for several seconds. Is there any way to speed this up outside of comparing the old list to the new one and only removing/adding the items that have changed?

$("#myselect").children.remove();

$.each(myList, function(i, val) {
   $("<option>").attr("value", val.myID)
                .text(val.myText)
                .appendTo("#myselect");
});
+2  A: 

What if you create a new element and switch it out?

var newSelect = $("<select></select>");
$.each(myList, function(i, val) {
    $("<option>").attr("value", val.myID)
                 .text(val.myText)
                 .appendTo(newSelect);
});
$("#myselect").replaceWith(newSelect);
singingwolfboy
Sounds like it should work, and that would be simple as pie. I'll report back. :)
Chris
This speeds it up by several seconds and fixes the "animated" removal. IE6 is still a little slow, but this seems to be the best solution. Thanks!
Chris
+2  A: 

Although your code is much nicer, if it's too slow, go for the direct route (I've done it in the past, before using jQuery, and it was instant in all browsers, including IE6). Just remove all the children from the select by removing the html:

$("#myselect").html('');

And modify the loop so that you create the html for each option, and insert it into the select by using

$('#myselect').html(optionsHTML);

Depending on the performance, you could try a middle ground between this solution and karim79's solution (ie. remove the options with html(), and append them using the array instead of creating plain HTML).

salgiza
I also like this idea, as you don't have to blow away the select element. .html('') fixed the children.remove() problem as well.
Chris
This solved my performance issue where $("#myListBox").empty() in IE8 was taking over 3 seconds to clear a listbox where Firefox was taking 30ms. To be fair there was over 2500 items, but that doesn't explain the orders of magnitude difference in performance.
Nick