[英]javascript/jquery remove or delete option from select
我需要在某些情况下从选择中删除一个选项。
基本上:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
有人知道我的代码来实现这个目标吗?
非常感谢。
按值删除:
$("#select1 option[value=1]").remove();
按文字删除:
$("#select1 option:contains(Text)").remove();
编辑
由于id在文档中是唯一的,因此无需将其与父选择元素相关联。 你可以做的很简单
$("#option1").remove();
jQuery的:
$("#option1").remove();
要么
$("#select").remove("#option1");
和经典的JavaScript方法:
var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);
我见过很多人都有这个问题。 我创建了这个可能有用的脚本。 希望你喜欢:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.