Javascript 使用 jQuery 在下拉列表中设置默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4781420/
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
Set the default value in dropdownlist using jQuery
提问by Hogsmill
I have many options in my dropdownlist like:
我的下拉列表中有很多选项,例如:
<option value="1">it's me</option>
I need to select the option who have value it's meinside the tag, not by attribute like 1
.
我需要选择谁具有价值的选择是我的标签内,而不是像属性1
。
How can I do this using jQuery?
我如何使用 jQuery 做到这一点?
回答by kylewelsby
if your wanting to use jQuery for this, try the following code.
如果您想为此使用 jQuery,请尝试以下代码。
$('select option[value="1"]').attr("selected",true);
Updated:
更新:
Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.
根据 Vivek 的评论,正确指出史蒂文斯皮尔伯格希望通过其文本值选择该选项。
Here below is the updated code.
下面是更新后的代码。
$('select option:contains("it\'s me")').prop('selected',true);
You need to use the :contains(text)
selector to find via the containing text.
您需要使用:contains(text)
选择器通过包含文本进行查找。
Also jQuery propofferes better support for Internet Explorer when getting and setting attributes.
此外,jQuery prop在获取和设置属性时为 Internet Explorer 提供了更好的支持。
回答by Hogsmill
You can just do this:
你可以这样做:
$('#myCombobox').val(1)
回答by oditiwebs.com
val() should handle both cases
val() 应该处理这两种情况
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
回答by Vivek
$("#dropdownList option[text='it\'s me']").attr("selected","selected");
回答by Franco
$('#userZipFiles option').prop('selected', function() {
return this.defaultSelected;
});
回答by Harish
jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");
回答by ashish.chotalia
This is working fine:
这工作正常:
$('#country').val($("#country option:contains('It\'s Me')").val());
回答by Mark Robinson
One line of jQuery does it all!
一行 jQuery 就搞定了这一切!
$("#myCombobox option[text='it\'s me']").attr("selected","selected");