Select the first item to select

How to always select the first element in an HTML select box using an index? I don't want to use val () to select.

+2


source to share


4 answers


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);

      

+7


source


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

      

or

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

      



Assuming by choice you mean to make the first option the selected one.

See Selectors / first

+1


source


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

      

+1


source


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.

0


source







All Articles