jQuery将空白选项添加到列表顶部并选择现有下拉列表 [英] jQuery add blank option to top of list and make selected to existing dropdown
本文介绍了jQuery将空白选项添加到列表顶部并选择现有下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个下拉列表
<select id="theSelectId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
这就是我想要的
<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.
尝试了但没有用
// 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>');
推荐答案
这行得通:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
萤火虫输出:
<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>
如果你想颠倒顺序,你也可以使用 .prependTo
:
You could also use .prependTo
if you wanted to reverse the order:
$("<option>", { value: '', selected: true }).prependTo("#theSelectId");
这篇关于jQuery将空白选项添加到列表顶部并选择现有下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文