jQuery jQuery将空白选项添加到列表顶部并选择现有下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1070828/
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
jQuery add blank option to top of list and make selected to existing dropdown
提问by Phill Pafford
So I have a dropdown list
所以我有一个下拉列表
<select id="theSelectId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is what I would like
这是我想要的
<select id="theSelectId">
<option value="" selected="selected"></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Trying to add a blank option before and set it to this, want to enforce the user to select a value from the original list but would like it to be blank when they see the option they have to choose.
之前尝试添加一个空白选项并将其设置为此,希望强制用户从原始列表中选择一个值,但希望在他们看到他们必须选择的选项时它是空白的。
Trying this but not working
尝试这个但不起作用
// Add blank option
var blankOption = {optVal : ''};
$.each(blankOption, function(optVal, text) {
$('<option></option>').val(optVal).html(text).preprendTo('#theSelectId');
});
and I have tried this but is clears out the other values
我已经尝试过了,但是清除了其他值
$('#theSelectId option').prependTo('<option value=""></option>');
回答by Sampson
This worked:
这有效:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
萤火虫输出:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
.prependTo
如果您想颠倒顺序,也可以使用:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
回答by Snoozer
Solution native Javascript :
解决方案原生 Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL