使用 jQuery 将选择框值设置为第一个选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18393040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:31:00  来源:igfitidea点击:

Use jQuery to set select box value to first option

javascriptjquery

提问by Kim Prince

I am dynamically populating a select box with options. When I do this, I want the value of the select box to be the value of the first option (a 'default option', if you like). Sounds really simple, but I just can't get it to work.

我正在用选项动态填充选择框。当我这样做时,我希望选择框的值是第一个选项的值(“默认选项”,如果你愿意的话)。听起来很简单,但我就是无法让它工作。

var myElement = $('select[name="myName"]');

.... tried the following three variations

.... 尝试了以下三种变体

// myElement.find('option').first().prop('selected', 'selected');
// myElement.val(myElement.find('options').first().val());
myElement.prop('selectedIndex', 0);

...but the following line gives a blank alert

...但以下行给出了一个空白警报

alert(myElement.val());

Where am I going wrong?

我哪里错了?

回答by Sushanth --

optionsshould be option

选项应该是选项

myElement.find('option:eq(0)').prop('selected', true);

You can use the eqselector on the option to select the first option.

您可以使用eq选项上的选择器来选择第一个选项。

If you know the value of the first option. Then you could simply do

如果你知道第一个选项的价值。那么你可以简单地做

myElemeent.val('first value') // Which selects the option by default

The 2nd case you tried should work, unless you are not calling at the right point . i.e; waiting for the ajax response to be completed.

您尝试的第二种情况应该有效,除非您没有在正确的时间打电话。IE; 等待 ajax 响应完成。

Try calling that inside the doneor the success(deprecated) handler

尝试在donesuccess(不推荐使用的)处理程序中调用它

回答by Yotam Omer

You almost got it, drop the 's' in 'options':

你几乎明白了,去掉 'options' 中的 's':

myElement.val(myElement.find('option').first().val());

Working jsFiddle

工作 jsFiddle

回答by Marin B?nzari

You could also use next code:

您还可以使用下一个代码:

myElement[0].selectedIndex = 0;

This get's the Dom element (not jQuery object), works with vanilla Javascript and uses it to set the first option as the selected one based on it's index.

这个 get 是 Dom 元素(不是 jQuery 对象),使用 vanilla Javascript 并使用它根据它的索引将第一个选项设置为选定的选项。

回答by Nima Izadi

If you want to be sure that your option has a value and is not a placeholder you can do:

如果您想确保您的选项具有值而不是占位符,您可以执行以下操作:

$('select option').filter( function (index, option) {
  return option.attributes.value
}).val()

That way you'll check if the HTML node has attribute valueand is not empty.

这样你就可以检查 HTML 节点是否有属性value并且不为空。