Select the first item to select
You can use : first selector:
var firstOption = $('#selectId option:first');
Then you can get parameter value firstOption.val();
or option textfirstOption.text();
And install it as selected:
//firstOption.prop('selected', true); since jQuery 1.6 is known to be faster way
firstOption.attr('selected', true);
Edit: If you only need to set the selected parameter, use the selectedIndex attribute:
$('#selectId').attr('selectedIndex', 0);
source to share
atr ('selected', 'selected');
It's not clear what jQuery is doing. attr
sets a DOM property, not an HTML attribute value; in fact setting the selected
HTML attribute will not necessarily change the selected option as the attribute only controls the default on the field. (excluding IE due to bug.)
attr('selected', true)
would be more appropriate. However, since any non-empty string evaluates true
to a boolean context, this will still work.
Anyway ... sometimes it's better to use regular DOM properties rather than force everything into a set of operations provided by jQuery. JQuery is intended to be a JS and DOM add-on, not a complete replacement. Your suggestion in the comments:
$('#select1').get(0).selectedIndex= 0;
is a more natural way to select the first option IMO and is much faster than a jQuery query to parse and implement a selector.
source to share