使用核心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>') ;

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


当前回答

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

其他回答

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

把html改成新数据怎么样?

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

另一个例子:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

第一行代码将删除选择框的所有选项,因为没有提到选项查找标准。

第二行代码将添加带有指定值("testValue")和文本("TestText")的选项。

为什么不直接使用javascript呢?

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