Home > Software design >  Filter Selected options when values included inside an array
Filter Selected options when values included inside an array

Time:01-12

I have this javascript code :

<script> 
var NotWanted = ['apple','banana','lemon'];
</script>

and this HTML code:

<select id="Fruits">     
    <option value="apple">Red apple</option>     
    <option value="banana">Yellow banana</option>     
    <option value="orange">Orange orange</option>     
    <option value="lemon">Yellow lemon</option> 
</select>  

how can I hide the 3 not wanted elements based on their value ?

Real data have more than 100 options so I should find a way to filter it for many elements.

Whatever I found while searching is based on the description of the select menu and not on the values.. My guess is I should try and add a class or an ID in each select value ?

CodePudding user response:

If you want to select all the <option> having the attribute value set to a given value, you can use the css attribute selector [value="apple"] to select, for example the option having the value attribute set to apple.

Since you showed a javascript array, I assumed you were asking for a javascript solution. So you may just loop through all the NotWanted array items, select the corresponding option and hide it setting its display to none.

var NotWanted = ['apple','banana','lemon'];
NotWanted.forEach(option =>
  document.querySelector(`option[value="${option}"]`).style.display = 'none');
<select id="Fruits">     
    <option value="apple">Red apple</option>     
    <option value="banana">Yellow banana</option>     
    <option value="orange">Orange orange</option>     
    <option value="lemon">Yellow lemon</option> 
</select>  

CodePudding user response:

You can add hidden to each of them.

const notWanted = ['apple','banana','lemon'];

const fruits = document.querySelector("#Fruits");
notWanted.forEach(f => fruits.querySelector(`[value=${f}]`).hidden = true);
<select id="Fruits">     
    <option value="apple">Red apple</option>     
    <option value="banana">Yellow banana</option>     
    <option value="orange">Orange orange</option>     
    <option value="lemon">Yellow lemon</option> 
</select> 

  • Related