So this is the working html for adjusting the zoom What I need to do now is how to hide the 200 option with an if condition using javascript. So if a variable is greater than the 200 option, I need to hide it.
`<div id="zoomAdjuster' >
<span>Zoom</span>
<select name="chooseAZoom">
<option value="100" selected>100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
</select>
</div>
`
Please help, I don't know much about this language. Thank you.
CodePudding user response:
You can select the select
using any document query method and then select the options. Then iterate the options and check for the value. If value is grater than 200 then add a class to hide it
const z = document.getElementsByName('chooseAZoom')[0].querySelectorAll('option').forEach((elem) => {
if (elem.value >= 200) {
elem.classList.add('hideOption')
}
})
.hideOption {
display: none
}
<div id="zoomAdjuster" >
<span>Zoom</span>
<select name="chooseAZoom">
<option value="100" selected>100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
</select>
</div>
CodePudding user response:
You can also remove the option
tags from the DOM. By:
- Selecting the
select
tag from the DOM, then get its childrenoption
tags, put those in an array with the spread syntax. - Filtering the array and remove the
option
tag with thevalue
of 200, if your variable is larger than 200. Else keep the array. - Clear all the
option
tags insideselect
, then loop through the filtered array and appending the option tags back toselect
let yourVariable = 201;
const select = document.querySelector('select[name=chooseAZoom]');
const optArr = [...select.children];
const newOptArr = optArr.filter(opt => {
if (yourVariable > 200)
return opt.value != 200;
return true;
})
select.innerHTML = "";
newOptArr.forEach(opt => select.appendChild(opt));
<div id="zoomAdjuster" >
<span>Zoom</span>
<select name="chooseAZoom">
<option value="100" selected>100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
</select>
</div>