使用 jquery 设置下拉值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17222165/
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 18:40:02  来源:igfitidea点击:

Set Dropdown value using jquery

jquery

提问by user2437845

In the first step, I have a set of values which are fed to a dropdown.

在第一步中,我将一组值输入到下拉列表中。

In the next step, I want to SET the value of the dropdown from the set of the values which are fed to it in the first step.

在下一步中,我想从第一步中提供给它的一组值中设置下拉列表的值。

Could anyone let me know the syntax in jquery?

谁能让我知道 jquery 中的语法?

回答by cssyphus

If it is, say, the 4th item in the dropdown, you can say:

如果是下拉列表中的第 4 项,您可以说:

$('select>option:eq(3)').prop('selected', true);  //zero-based

Note that older versions of jQuery used .attr instead of .prop

请注意,旧版本的 jQuery 使用 .attr 而不是 .prop



Here are some other methods:

以下是一些其他方法:

Imagine a select box like this:

想象一个这样的选择框:

<select name="options">
  <option value="1">Red</option>
  <option value="2" selected="1">Green</option>
  <option value="3">Blue</option>
</select>

You can get the 3rd value this way:

您可以通过这种方式获得第三个值:

$('[name=options]').val( 3 );//To select Blue

Using the text:

使用文本:

$('[name=options] option').filter(function() { 
    return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);

Reset it this way:

以这种方式重置它:

$('[name=options]').val( '' );