jQuery 从下拉列表中删除一个选项,给定选项的文本/值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1982449/
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 12:31:16  来源:igfitidea点击:

jQuery to remove an option from drop down list, given option's text/value

jquerydrop-down-menu

提问by Arnkrishn

I have a drop down list and would like to remove an option from it, given the text/value of that particular option. Is it possible using jQuery? Just like 'append' which adds an option to the drop down list, is there a function to remove an option?

鉴于该特定选项的文本/值,我有一个下拉列表并希望从中删除一个选项。是否可以使用jQuery?就像在下拉列表中添加选项的“附加”一样,是否有删除选项的功能?

I tried searching for it but all I got were examples where the entire set of options in the drop down list are removed, which is not what I seek.

我尝试搜索它,但我得到的只是删除下拉列表中的整个选项集的示例,这不是我所寻求的。

cheers

干杯

回答by Y. Shoham

$("option[value='foo']").remove();

$("option[value='foo']").remove();

or better (if you have few selects in the page):

或更好(如果页面中的选择很少):

$("#select_id option[value='foo']").remove();

$("#select_id option[value='foo']").remove();

回答by Elvis Ciotti

Once you have localized the dropdown element

本地化下拉元素后

dropdownElement = $("#dropdownElement");

Find the <option>element using the JQuery attribute selector

<option>使用 JQuery属性选择器查找元素

dropdownElement.find('option[value=foo]').remove();

回答by Raj Kumar

$('#id option').remove();

This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

这将清除下拉列表。如果你想清除选择值然后$("#id option:selected").remove();

回答by Vicky

First find the class name for particular select.

首先找到特定选择的类名。

$('#id').val('');
$('#selectoptionclassname').selectpicker('refresh');

回答by Mahmood

I know it is very late but following approach can also be used:

我知道现在很晚了,但也可以使用以下方法:

<select id="type" name="type" >
    <option value="Permanent" id="permanent">I am here to stay.</option>
    <option value="toremove" id="toremove">Remove me!</option>
    <option value="Other" id="other">Other</option>
</select>

and if I have to remove second option (id=toremove), the script would look like

如果我必须删除第二个选项 (id=toremove),脚本看起来像

$('#toremove').hide();