Jquery remove select options based on text input
I'm trying to do the following:
I have an input <input type="text" value="red,yellow,blue" id="colors" />
and a dropdown list
<select name="colors_dropdown" id="colors_dropdown">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
I want to开发者_Python百科 remove the select options that are in the text input. For example if text input value=red,blue
the dropdown should have just option yellow
.
I was able to make arrays of the comma separated values in the text input and values in dropdown options.
var selected_colors = $('#colors').val().split(","); //array of colors from text input
var all_colors = $.map($("#colors_dropdown")[0].options, function(option)
{
return option.value; //array of all colors from dropdown
});
Based on that, I'm looking for a way to populate the dropdown list with all colors except those in the selected_colors
arrays.
var selected_colors = $('#colors').val().split(","); //array of colors from text input
jQuery.each(selected_colors, function() {
$("#colors_dropdown option:[value='" + this + "']").remove();
//Or use text attribute:
//$("#colors_dropdown option:[text='" + this + "']").remove();
});
Working Demo: http://jsfiddle.net/83Vg9/2/
This will remove the exact matching colors. Using contains
could be remove all matching options for e.g. if the text box contains only e
it will remove yellow, blue, red, green everything...
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate each color
$.each(selected_colors, function(index, color) {
// iterate over each option & remove if necessary
$('#colors_dropdown option').each(function(){
if (this.value == color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
}
})
});
EDIT
Just realized that you don't need to use two each()
as shown above. Try this -
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate over each color and remove it from the dropdown
$.each(selected_colors, function(index, color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
});
精彩评论