KJai
KJai

Reputation: 1705

Select first item of a select

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

Upvotes: 3

Views: 8783

Answers (4)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828200

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.prop('selected', true); since jQuery 1.6 is known to be faster way
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);

Upvotes: 7

bobince
bobince

Reputation: 536795

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.

Upvotes: 0

karim79
karim79

Reputation: 342795

$('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

Upvotes: 1

Kieran Hall
Kieran Hall

Reputation: 2627

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

Upvotes: 1

Related Questions