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

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


当前回答

基于mauretto的回答,下面的内容更容易阅读和理解:

$('#mySelect').find('option').not(':first').remove();

要删除所有选项,除了一个具有特定值的选项,您可以使用以下命令:

$('#mySelect').find('option').not('[value=123]').remove();

如果要添加的选项已经存在,那就更好了。

其他回答

这将用一个新的mySelect替换现有的mySelect。

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;

另一种方法:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

在这个链接下,有一些好的实践https://api.jquery.com/select/

只需替换html即可

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
    var d = data[i];
    var option = $('<option/>').val(d.id).text(d.title);
    select.append(option);
}
select.val('');