Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first element in the dropdown using jquery?

I want to know how to select the first option in all select tags on my page using jquery.

tried this:

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

But didn't work

like image 625
Amr Elgarhy Avatar asked Sep 08 '09 15:09

Amr Elgarhy


People also ask

How do I select the first element in a Dropdownlist using jQuery?

Select the <select> element using JQuery selector. This selector is more specific and selecting the first element using option:nth-child(1). This will get access to the first element (Index starts with 1).

How do I select the first item in a dropdown?

So you could use $("select"). prop("selectedIndex",0); for a quick way to select the first option on all dropdowns.

How do I get the first element of a list in jQuery?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).


1 Answers

Try this out...

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

Another option would be this, but it will only work for one drop down list at a time as coded below:

var myDDL = $('myID'); myDDL[0].selectedIndex = 0; 

Take a look at this post on how to set based on value, its interesting but won't help you for this specific issue:

Change the selected value of a drop-down list with jQuery

like image 110
RSolberg Avatar answered Oct 04 '22 16:10

RSolberg