Jaylen Jaylen - 3 months ago 9
jQuery Question

How can I find all options with a list of values using jQuery?

I am trying to find and hide multiple options in select menu.

Here is my menu

<select class="form-control" name="settingsColumnAggregate" id="settingsColumnAggregate">
<option value="None" selected="">None</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
<option value="Count">Count Distinct</option>
<option value="Max">Max</option>
<option value="Min">Min</option>
</select>


I want to hide the options where the value is in
["Sum","Ave","Max","Min"]


Here is what I tried

$('#settingsColumnAggregate')
.find('option[value="Sum"][value="Avg"][value="Max"][value="Min"]')
.hide();


But that is not working.

How can I correctly select multiple options by a list of values?
Here is what I tried

Answer

You have to loop through all the option or use filters()

var arr = ["Sum","Avg","Max","Min"];
$('#settingsColumnAggregate option').filter(function(){
    return jQuery.inArray( this.value, arr ) !== -1
}).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="settingsColumnAggregate" id="settingsColumnAggregate">
    <option value="None" selected="">None</option>
    <option value="Sum">Sum</option>
    <option value="Avg">Avg</option>
    <option value="Count">Count Distinct</option>
    <option value="Max">Max</option>
    <option value="Min">Min</option>
</select>

Or use find and multiple selector which is bit messy though and hard to read. You forgot to add , in your code which treats it as single selector.

$('#settingsColumnAggregate')
.find('option[value="Sum"],option[value="Avg"],option[value="Max"],option[value="Min"]')
.hide();
Comments