skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. 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 insideselect, 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search