tags:

views:

228

answers:

4

How do I always select the first item in a HTML select box using index? I do not want to use val() to select.

+1  A: 
$('select option:first').get(0).select();

or:

$('select option:first').attr('selected','selected');

Assuming that by select you mean make the first option the selected one.

See Selectors/first

karim79
+3  A: 

You can use the :first selector:

var firstOption = $('#selectId option:first');

Then you can get the option value by firstOption.val(); or the option text by firstOption.text();

And set it as selected:

firstOption.attr('selected', true);

Edit: If the only thing you want is to set the selected option, use the selectedIndex attribute:

$('#selectId').attr('selectedIndex', 0);
CMS
I checked and found that another way is to do $("#select1").get(0).selectedIndex = 0; Is this also a recommended way?
KJai
That would also work just as well. I can't say for certain, but I'd wager a guess there's less overhead with `$("#select").get(0).selextedIndex = 0` than CMS's alternative because the former only requires jQuery to find the select box and then sets its selected item via the DOM directly, rather than finding the Select, then getting its options, then selecting the first option, and then finally setting its selected attribute. Setting the selectedIndex is quite a bit more direct as it is less abstraction-layer-dependent. Anyone care to confirm or deny?
Nathan Taylor
@Nathan: Agree, I used :first because I wasn't sure if the OP wanted to get information about the first option. But for sure, if the user only wants to change the selected index, that's the way to go.
CMS
A: 
$("select option:first").attr('selected','selected');
Kieran Hall
A: 

attr('selected','selected');

Is misunderstanding what jQuery is doing a little. attr sets a DOM property, not an HTML attribute value; actually setting the selected HTML attribute would not necessarily change the selectedness of the option, because the attribute only controls the default state of the field. (except in IE due to a bug.)

attr('selected', true) would be more appropriate. However since any non-empty string evaluates to true in a boolean context, the above will still work.

Anyway... sometimes it's best to use normal DOM properties rather than forcing everything into the set of operations provided by jQuery. jQuery is supposed to be an addition to JS and DOM, not a complete replacement for it. Your suggestion in comments:

$('#select1').get(0).selectedIndex= 0;

is a more natural way to select the first option IMO, and much much faster than asking jQuery to parse and implement a selector.

bobince