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.
$(‘select option:nth(0)’).attr(“selected”, “selected”);
But didn’t work
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.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:
Your selector is wrong, you were probably looking for
This will work also:
Ana alternative Solution for RSolgberg, which fires the
'onchange' event if present:
$("#DDLID").val( $("#DDLID option:first-child").val() );
What you want is probably:
What this code
is doing is setting the “selected” attribute to “selected”
If you want the selected options, regardless of whether it is the first-child, the selector is:
I’m answering because the previous answers have stopped working with the latest version of jQuery. I don’t know when it stopped working, but the documentation says that .prop() has been the preferred method to get/set properties since jQuery 1.6.
This is how I got it to work (with jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
I am using knockoutjs and the change bindings weren’t firing with the above code, so I added .change() to the end.
Here’s what I needed for my solution:
$('select option:nth-child(1)').prop("selected", true).change();
See .prop() notes in the documentation here: http://api.jquery.com/prop/