disable other options in select except the selected

Disable Other Options in Select Except the Selected

Have you ever encountered a situation where you want to disable other options in a select dropdown except the selected one? It's a common use case in forms where you don't want users to select multiple options.

Here's how you can achieve this using jQuery:


$('select').on('change', function() {
  var selectedOption = $(this).val();

  $('select option:not(:selected)').prop('disabled', true);
});

This code listens for a change event on the select dropdown and gets the value of the selected option. It then disables all other options except the selected one using the prop() method.

If you want to achieve this without jQuery, you can use plain JavaScript:


var select = document.querySelector('select');

select.addEventListener('change', function() {
  var selectedOption = this.value;

  Array.from(this.options).forEach(function(option) {
    if (option.value !== selectedOption) {
      option.disabled = true;
    }
  });
});

This code does the same thing as the jQuery code, but it uses the addEventListener() method to listen for the change event and loops through all options to disable them except the selected one.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe