I have a dropdown in a web page with 3830 elements in it. I know, excessive but whatever.
In jquery I get the selected option value using the statement:
$( ‘#institutionCombo :selected’ ).val();
There is a noticeable pause before the selection is found. Once I get that value I insert it into a textbox on the page, so I know how fast. Plus I’ve checked it using breakpoints in Firebug.
If I go old school and use this javascript:
var div = document.getElementById( ‘maindiv’ );
var select = div.getElementsByTagName( ‘select’ )[ 0 ];
var ix = select.selectedIndex;
var instId = select.options[ ix ].value;
This speed is instananeous.
Is there something inherit in jquery that makes the :selected selector so slow when the numbers get too high? I’d like to stick with jquery throughout in my scripts, does anyone have a suggestion to speed up finding the selected option in jquery?
Thanks,
Craig
There is no need to call the :selected when getting the val of a select box.
The default behavior is to get the selectedIndex
As noted in the comment, If you need to access the text of that option you can use
although if you know you need the text property and its different from the value you may just want to use the selectedIndex directly.
Here is the snippet from the jquery source (v1.3)
When you call the :selected selector that is going loop through all the select elements decendents looking for the .selected property to be set and will return an array of any. Either way you do this it will loop all decendents, so don’t do this.