Jquery/Javascript: Compare two dropdown min and max values?

Viewed 238

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 Answers

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>

Related