Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first item of a select

Tags:

jquery

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

like image 483
KJai Avatar asked Dec 17 '25 00:12

KJai


1 Answers

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);
like image 131
Christian C. Salvadó Avatar answered Dec 19 '25 16:12

Christian C. Salvadó