如何使用 Jquery 在下拉列表中设置值?

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

How to set value in dropdown using Jquery?

jqueryasp.net-mvc

提问by sreenu

Hi I am setting a value in a drop down using jquery in the following ways.

嗨,我正在通过以下方式使用 jquery 在下拉列表中设置一个值。

$("#dropDownItems option[value='--Select--']").attr('selected', 'true');

 $("#dropDownItems option[value='--Select--']").attr('selected', 'selected');

But none of these are working for FireFox! and is working fine for remaining browsers.

但是这些都不适用于 FireFox!并且在其余浏览器上运行良好。

Can any one help me out?

谁能帮我吗?

回答by Josh Mein

This should do the trick for you.

这应该对你有用。

$('#dropdownID').val("Value to be selected");

回答by Chris Fulstow

$("#dropDownItems").val("--Select--");

Or, if you just want to select the first option regardless of its value, you can define this helper function:

或者,如果您只想选择第一个选项而不考虑其值,您可以定义此辅助函数:

$.fn.selectFirst = function () {
    return $(this).find("option:first").attr("selected", "selected").end();
}

Then use it like this:

然后像这样使用它:

$("#dropDownItems").selectFirst();

回答by user872152

If you want to set the default value and it is the first element, you can do:

如果你想设置默认值并且它是第一个元素,你可以这样做:

$('#dropDown')[0].selectedIndex=0;

回答by Saket

I guess there are multiple ways to do it. The easiest way:

我想有多种方法可以做到这一点。最简单的方法:

$("#dropdownID").val("dropdownValue");

This will work just fine, but it won't fire the change event if you have in any case. To resolve it, use it like below:

这将工作得很好,但在任何情况下它都不会触发更改事件。要解决它,请使用它,如下所示:

$("#dropdownID").val("dropdownValue").change();

Other possible ways:

其他可能的方式:

$("#dropdownID").attr('selected','selected');

$("#dropdownID").prop('selected', true);

回答by shafi7468

try this

尝试这个

$('[id*=_dropdown]').val("--Select--");