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


Try this out...

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

Another option would be something like 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


Your selector is wrong, you were probably looking for

$('select option:nth-child(1)')

This will work also:

$('select option:first-child')

Ana alternative Solution for RSolgberg, which fires the 'onchange' event if present:

$("#target").val($("#target option:first").val());

How to make first option of <select > selected with jQuery?

链接地址: http://www.djcxy.com/p/83920.html

上一篇: 在选择框中单击触发器在jQuery中不起作用

下一篇: 如何使用jQuery选择下拉列表中的第一个元素?