Home > Mobile >  How do I display distinct options in the select input so that when I choose an option, there are no
How do I display distinct options in the select input so that when I choose an option, there are no

Time:02-02

I have 3 select input, all with 4 options. And for example, on the first select, i selected option 3, the remaining select shall not have option 3 in their option. Same goes when in the 2nd select, when i select option 4, the other 2 select shall not show option 4. So the first select should only show the selected option (Option 3), option 1 and 2. and last select only show option 1 and 2.

View Starting and Ending Result

I tried this but it doesn't work out well

$(document).ready(function() {
  var selects = document.querySelectorAll('select');

  for (var i = 0; i < selects.length; i  ) {
    selects[i].addEventListener('change', function() {
      var selectedOption = this.value;
      for (var j = 0; j < selects.length; j  ) {
        if (selects[j] !== this) {
          var options = selects[j].options;
          for (var k = 0; k < options.length; k  ) {
            if (options[k].value === selectedOption) {
              options[k].style.display = 'none';
            } else {
              options[k].style.display = 'block';
            }
          }
        }
      }
    });
  }
});

CodePudding user response:

You can use a data attribute and selectedIndex of the changed select to show and hide the other select options:

var $selects = $('select');

$selects.on('change', e => {
  $selects.not($(e.currentTarget)) // get selects that aren't current changed
    .each((index, select) => {
      if (e.currentTarget.dataset.selected) {
        select.options[e.currentTarget.dataset.selected].style.display = 'block';  // show any previous selected
      }

      select.options[e.currentTarget.selectedIndex].style.display = 'none';  // hide same index option in other selects
    });
      
    e.currentTarget.dataset.selected = e.currentTarget.selectedIndex;  // set data attrbiute for previous selected
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>

  • Related