简体   繁体   中英

How to hide an <option> in <select> with an if condition?

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.

EDIT: I was wrong explaining it, so if a variable is greater than another variable, I need to hide the 200 option and display the 100, 300, and 400.

<div id="zoomAdjuster' class="centerAlign">
  <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.

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" class="centerAlign"> <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>

You can also remove the option tags from the DOM. By:

  • Selecting the select tag from the DOM, then get its children option tags, put those in an array with the spread syntax.
  • Filtering the array and remove the option tag with the value of 200, if your variable is larger than 200. Else keep the array.
  • Clear all the option tags inside select , then loop through the filtered array and appending the option tags back to select

 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" class="centerAlign" > <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM