javascript/jquery 从选择中删除或删除选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2424468/
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
javascript/jquery remove or delete option from select
提问by AndrewC
I need to delete an option from a select in certain circumstances.
在某些情况下,我需要从选择中删除一个选项。
Basically:
基本上:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
Anyone know the code for me to achieve this?
有人知道我实现这一目标的代码吗?
Many thanks.
非常感谢。
采纳答案by rahul
Edit
编辑
Since id is unique in the document no need to relate it to the parent select element. You can do simply
由于 id 在文档中是唯一的,因此无需将其与父 select 元素相关联。你可以简单地做
$("#option1").remove();
回答by gnarf
Remove by Value:
按值删除:
$("#select1 option[value=1]").remove();
Remove by Text:
按文本删除:
$("#select1 option:contains(Text)").remove();
回答by Andy E
jQuery:
jQuery:
$("#option1").remove();
or
或者
$("#select").remove("#option1");
And the classic javascript method:
和经典的 javascript 方法:
var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);
回答by Rafael
I have seen many people with this problem. I have created this script that could be useful. Hope you like it:
我见过很多人有这个问题。我创建了这个可能有用的脚本。希望你喜欢:
var robable = {
init: function() {
robable.get_selected_option_from_select();
},
get_selected_option_from_select: function() {
$(".robable").off().on("change", function() {
if ($(this).val() !== "") {
robable.add_to_list($(this));
}
});
},
remove_option_from_select: function(select_id, value) {
$("#" + select_id + " option[value='" + value + "']").remove();
},
add_option_to_select: function(select_id, value, text) {
$('#' + select_id).append('<option value="' + value + '">' + text + '</option>');
},
add_to_list: function(select) {
option_text = $(".robable option[value='" + select.val() + "']").text();
//Add to list
$('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>");
robable.remove_from_list();
//Remove from select
robable.remove_option_from_select(select.attr("id"), select.val());
},
remove_from_list: function() {
$(".filter-remove").off().on("click", function() {
var select_id = $(this).data('parent-id');
var option_value = $(this).closest("li").data('value');
var option_text = $(this).closest("li").data('text');
//Add to select
robable.add_option_to_select(select_id, option_value, option_text);
//Remove from list
$(this).closest("li").remove();
});
}
};
robable.init();
<!DOCTYPE html>
<html>
<head>
<title>Select Robables</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<ul id="list"></ul>
</body>
</html>

