Javascript / jquery remove or remove parameter from

I need to remove an option from a selection in certain circumstances.

Basically:

if(mystatement == true) { //remove item with id 'option1' from select of id 'select1' } 

Does anyone know the code for me to achieve this?

Many thanks.

+7
javascript jquery
source share
4 answers

Edit

Since id is unique in the document, there is no need to associate it with the parent selection element. You can do just

 $("#option1").remove(); 
+8
source share

Delete by value:

 $("#select1 option[value=1]").remove(); 

Delete by text:

 $("#select1 option:contains(Text)").remove(); 
+14
source share

JQuery

 $("#option1").remove(); 

or

 $("#select").remove("#option1"); 

And the classic javascript method:

 var option1 = document.getElementById("option1"); document.getElementById("select1").removeChild(option1); 
+3
source share

I have seen many people with this problem. I created this script that may be useful. I hope you will 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> 
0
source share

All Articles