Reputation: 1
I have this javascript code :
var NotWanted = ['apple','banana','lemon'];
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 ?
Upvotes: 0
Views: 55
Reputation: 22365
this way:
(both previous answers let Red apple
as default select)
-- hidden
property is also good, but not always supported on some older browser versions.
But anyway, to respect the HTML logic, an unusable option must be marked as disabled.
function filterSelectOption( select_ID, notWanted_Arr )
{
const eSelect = document.getElementById(select_ID);
eSelect.value = ''; // === select default is none
[...eSelect.options] // same as Array.from(eSelect.options)
.forEach( opt =>
{
opt.disabled = notWanted_Arr.includes( opt.value );
// or (without needs of css) :
// opt.disabled = opt.hidden = notWanted_Arr.includes( opt.value );
if (!opt.disabled && eSelect.value === '')
opt.selected = true;
// eSelect.value = opt.value; // set the default select
})
}
/* use CSS to temporary "remove" unwanted elements */
select option[disabled] {
display: none;
}
<button
onclick="filterSelectOption('Fruits',['apple','banana','lemon'])">
no apple or banana or lemon
</button>
<button
onclick="filterSelectOption('Fruits', ['orange','lemon'] )">
no orange or lemon
</button>
<button
onclick="filterSelectOption('Fruits', [])">
show all
</button>
<br><br>
<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>
Upvotes: 1