使用核心jQuery,如何删除一个选择框的所有选项,然后添加一个选项并选择它?

我的选择框如下。

<Select id="mySelect" size="9"> </Select>

编辑:下面的代码有助于链接。但是,(在Internet Explorer中).val('whatever')没有选择添加的选项。(我确实在.append和.val中使用了相同的“value”。)

$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');

编辑:试图让它模仿这段代码,每当页面/表单重置时,我使用以下代码。这个选择框由一组单选按钮填充。.focus()更接近,但该选项没有像.selected= "true"那样显示为已选中。我现有的代码没有问题-我只是想学习jQuery。

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";

编辑:所选的答案接近我所需要的。这招对我很管用:

$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;

但这两个答案都让我找到了最终的解决方案。


当前回答

最简短的回答:

$('#mySelect option').remove().append('<option selected value="whatever">text</option>');

其他回答

$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;

为什么不直接使用javascript呢?

document.getElementById("selectID").options.length = 0;

只需替换html即可

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');

首先清除所有现有的选项,执行第一个选项(——Select——) 使用循环逐个添加新的选项值 $ (' # ddlCustomer ');(选项:不(:第一)).remove (); For (var I = 0;i < oResult.length;我+ +){ $ (" # ddlCustomer”)。添加新选项(oResult[我]。CustomerName, oResult[我]。CustomerID + '/' + oResult[i].ID)); }

使用jquery prop()清除所选选项

$('#mySelect option:selected').prop('selected', false);