jQuery 如何通过jquery将下拉列表的选定值设置为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6734747/
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
How to set selected value as empty for dropdownlist via jquery
提问by Iori-kyo
I am using jquery to populate dropdownlist, the codes are like below:
我正在使用 jquery 来填充下拉列表,代码如下:
var myOptions = {
val1 : 'text1',
val2 : 'text2',
val3 : ''
};
$.each(myOptions, function(val, text) {
$('#mySelect').append( $('<option></option>').val(val).html(text)
);
});
now I have populate 3 items in my dropdown, and now I want to set my dropdownlist selected value with '', just like:
现在我在下拉列表中填充了 3 个项目,现在我想用 '' 设置我的下拉列表选择值,就像:
$("#mySelect option contain('')").attr(selected,true).
Actually, this will get all 3 items so that it will not set '' as selected value, is there any way that i can do this?
实际上,这将获得所有 3 个项目,因此它不会将 '' 设置为选定值,有什么办法可以做到这一点?
回答by Tim Büthe
$("#mySelect option[value='']").attr('selected', true)
回答by Josh
It will do the same .
$('#elemtId').val('')
Will achieve same result
它也会这样做。
$('#elemtId').val('')
将达到相同的结果
回答by CodingSolutions
What I am getting from your question is that you want to set the selected value as empty.
If so, you can try$(“#elementId”).val('');
e.g.$(“#val3”).val('');
我从你的问题中得到的是你想将选定的值设置为空。
如果是这样,您可以尝试$(“#elementId”).val('');
例如$(“#val3”).val('');
otherwise if you want to set any specific value as selected by finding the option by its text, try this.
否则,如果您想通过按文本查找选项来将任何特定值设置为所选值,请尝试此操作。
The last thing you might want to do as you mentioned above is that you want to set val3 as selected, i.e. setting a specific known option as selected, try thisI have tried all these ways...Hope this helps :)
如上所述,您可能想要做的最后一件事是将 val3 设置为已选择,即将特定的已知选项设置为已选择,试试这个我已经尝试了所有这些方法......希望这会有所帮助:)