从 select jquery 中删除所有选项,但只有一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18866745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:38:50  来源:igfitidea点击:

remove all options from select jquery but only one

javascriptjqueryremoveall

提问by user1428798

I have a select that contain this values:

我有一个包含以下值的选择:

<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>

How can I delete all options but i would like to keep only

如何删除所有选项但我只想保留

 <option value="0">Autre...</option>

My problem is my list is dynamic sometimes I have 3,5,7,.... select + the last one <option value="0">Autre...</option>

我的问题是我的列表是动态的,有时我有 3,5,7,.... select + 最后一个 <option value="0">Autre...</option>

回答by adeneo

select all options, then exclude the one with that value :

选择所有选项,然后排除具有该值的选项:

$('#lstCities option[value!="0"]').remove();

FIDDLE

小提琴

回答by Arun P Johny

Try

尝试

$('#lstCities option:lt(-1)').remove()

Demo: Fiddle

演示:小提琴

回答by Arun P Johny

$('#lstCities option[value!=0]').remove()

You should remove by value and not rely on the position of the option element to keep.

您应该按值删除,而不是依赖于要保留的选项元素的位置。

回答by Cedric

If the option is always the last one, I hope this JavaScript code can help you:

如果选项总是最后一个,希望这段 JavaScript 代码可以帮助到你:

var lastNode = $("#lstCities option").last();
var option = { value:lastNode.val(), text:lastNode.text() };

$('#lstCities').find('option').remove().end().append($('<option>',{
        value:option.value,
        text:option.text,
}));

Learned from this post

从这个帖子学到

回答by jam

This worked for me:

这对我有用:

$("#selectList option").remove();