Disclaimer: This seems to have been asked in similar form several times already but none of the solutions has worked for me. Additionally most of the solutions appear to be 4+ years old (up to 12+), who knows what changed in that time, I certainly don't.
The Problem: I want to hide all options in a select and only "unhide" them depending on what is chosen in another select.
I have two selects:
<select id="pool" name="pool" onchange="cause_mod()">
<option value="none" selected disabled hidden>Pool</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
and:
<select id="cause" name="cause">
<option value="none" selected hidden="true">cause/option>
<option value="sale" hidden="true">sale</option>
<option value="withdraw" id="withdraw" hidden>withdraw</option>
<option value="deposit" style="display: none">deposit</option>
</select>
The three different variances are to show what i have already tried on the select-side.
I shan't post every variation of the javascript code as it simply would be too much. I will post three variations that i tried with the three variations in the second select:
function cause_mod(){
var pool = document.getElementById("pool");
var cause = document.getElementById("cause");
var deposit = document.querySelectorAll('option[value="deposit"]');
if(pool.value === "1"){
cause.options[1].setAttribute("hidden", true)
document.getElementById("withdraw").removeAttribute("hidden")
deposit.style.display = "";
}
else if(pool.value === "2"){
pretty much the opposite
}
}
I wonder if there is any convenient method (although at this point I'll take inconvenient as well) to "grab" individual options from a select in order to .dosomething with it.
The hidden attribute shouldn't be set to the JavaScript Boolean true, it should just be present or set to the string "hidden":
const sel = document.querySelector("select");
sel.options[1].setAttribute("hidden", "hidden");
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
Now, if you have an option that should not have any value, set it to: value="", not value="none" because none is a string and therefore will become the value of the element.
Also, setting the CSS style.display property to an empty string is not acceptable as this attribute should be set to a valid CSS display value.
Additionally, querySelectorAll() returns a node list, which is an array-like object. Node lists don't have a value property. In your case, if you are looking for a single element on your page, use querySelector(), which will return the first element that matches the selector you supply or undefined if no match can be found. When there is a match, you can then access its DOM properties, like value.
Lastly, you should move your pool, cause and deposit variable declarations out of your function so that they are reinitialized each time the function is called, this is a wasted of resources to scan for the same elements that you already scanned for earlier.