2

I have two dropdowns. One has min values and the other has max values.

I'm trying to disable options from max dropdown if they are less than min values

<div>
  <select id="min">
    <option>Select min</option>
    <option value=0>0</option>
    <option value=1>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
    <option value=4>4</option>
    <option value=5>5</option>
  </select>

  <select id="max">
    <option>Select max</option>
    <option value=2>2</option>
    <option value=3>3</option>
    <option value=4>4</option>
    <option value=5>5</option>
    <option value=6>6</option>
    <option value=7>7</option>
  </select>
</div>

1

1 Answer 1

1

FYI: If you don't set the value attribute of an option element, then the value just becomes the text content of that option, so in your case, you don't need to set value on any of the options.

See additional comments inline:

let maxSelect = document.getElementById("max");
let minSelect = document.getElementById("min")

// When the first select's value is changed...
minSelect.addEventListener("change", function(){

  // Loop through all the <option> elements in the second list
  maxSelect.querySelectorAll("option").forEach(function(opt){
  
    // Check the option value to see if it is more than the value
    // of the first select. If so, disable it, otherwise enable it.
    // The prepended + implicitly converts the string values to numbers
    if(+minSelect.value > +opt.value){
      opt.disabled = true;
    } else {
       opt.disabled = false;   
    }
    
  });

});
<div>
  <select id="min">
    <option>Select min</option>
    <option>0</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>

  <select id="max">
    <option>Select max</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
  </select>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

https://jsfiddle.net/thorstorm1102/x7zsapy2/6/ Can you check here. if Input is 101. Wrong dropdown values are disabled
@Zanthoxylumpiperitum Oh, little bug there. We need to convert the select values to numbers (they are strings by default) for numeric comparisons to work. I'll update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.