Let’s suppose I have a <select> element:
<select id="foobar" name="foobar" multiple="multiple">
<option value="1">Foobar 1</option>
<option value="2">Foobar 2</option>
<option value="3">Foobar 3</option>
</select>
And let’s suppose I have an array of values, something like:
var optionValues = [2, 3];
How can I select the <option>s with values 2 and 3 most efficiently?
I’m working with a <select> that has thousands of <option>s, so doing it manually like this won’t work:
var optionElements = [];
$("#foobar").children().each(function() {
if($.inArray($(this).val(), optionValues)) {
optionElements.push($(this));
}
}
It’s just too slow. Is there a way to hand jQuery a list of values for the elements I need to select? Any ideas?
P.S. In case you’re wondering, I am in the middle of optimizing my jQuery PickList widget which currently sucks at handling large lists.
First of all, I want to thank you all for the awesome responses! I’m considering each one, and I will probably do benchmarks before I make a decision.
In the interim, I actually found an “acceptable” solution based on this answer to another question.
Here’s what I came up with (the last block, with the custom
filter()implementation, is where the magic happens):I doubt this is as efficient as any of the stuff you guys posted, but it has decreased the “Add” picklist operation time from about 10 seconds to 300ms on a 1500 item list.