本文翻译自:How do you remove all the options of a select box and then add one option and select it with jQuery?
Using core jQuery, how do you remove all the options of a select box, then add one option and select it? 使用核心jQuery,如何删除选择框的所有选项,然后添加一个选项并选择它?
My select box is the following. 我的选择框如下。
<Select id="mySelect" size="9" </Select>
EDIT: The following code was helpful with chaining. 编辑:以下代码有助于链接。 However, (in Internet Explorer) .val('whatever')
did not select the option that was added. 但是,(在Internet Explorer中) .val('whatever')
没有选择添加的选项。 (I did use the same 'value' in both .append
and .val
.) (我在.append
和.val
中都使用了相同的'value'。)
$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. 编辑:试图让它模仿这个代码,每当页面/窗体重置时,我使用以下代码。 This select box is populated by a set of radio buttons. 此选择框由一组单选按钮填充。 .focus()
was closer, but the option did not appear selected like it does with .selected= "true"
. .focus()
更接近,但该选项似乎没有像.selected= "true"
那样被选中。 Nothing is wrong with my existing code - I am just trying to learn jQuery. 我现有的代码没有任何问题 - 我只是想学习jQuery。
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. 编辑:选择的答案接近我需要的。 This worked for me: 这对我有用:
$('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution.. 但这两个答案都让我得到了最后的解决方案..
#1楼
参考:https://stackoom.com/question/CRM/如何删除选择框的所有选项-然后添加一个选项并使用jQuery选择它
#2楼
如果您的目标是从第一个选项中删除所有选项(通常是“请选择项目”选项),您可以使用:
$('#mySelect').find('option:not(:first)').remove();
#3楼
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
#4楼
This will replace your existing mySelect with a new mySelect. 这将使用新的mySelect替换现有的mySelect。
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
#5楼
为什么不只是使用普通的JavaScript?
document.getElementById("selectID").options.length = 0;
#6楼
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. 我在IE7中有一个错误(在IE6中工作正常),使用上面的jQuery方法将清除DOM中的选择而不是屏幕上的选择。 Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them. 使用IE Developer Toolbar我可以确认选择已被清除并拥有新项目,但在视觉上, 选择仍显示旧项目 - 即使您无法选择它们。
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options. 解决方法是使用标准的DOM方法/特性(如海报原版所示)来清除而不是jQuery - 仍然使用jQuery来添加选项。
$('#mySelect')[0].options.length = 0;