0

Is it possible to use jquery to filter select options to only show options with a certain value? Say I had this:

var testArray = ["foo", "bar"];

<select id="dropdown">
    <option>bar</option>
    <option>baz</option>
    <option>foo</option>
</select>

After my script executes, I'd like to be left with the following:

<select id="dropdown">
    <option>bar</option>
    <option>foo</option>
</select>
codenewb
  • 101
  • 1
  • 3
  • 12
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Joundill Sep 09 '20 at 03:16

1 Answers1

2

You can select all elements which are not in your array using .not() and $.inArray(), and then remove them using .remove().

See example below:

var testArray = ["foo", "bar"];
$("#dropdown option").not(function() {
  return $.inArray($(this).val(), testArray) > -1;
}).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
  <option>bar</option>
  <option>baz</option>
  <option>foo</option>
</select>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64