Skip to content
the poor coder

disable other options in select except the selected

Poor Man
Published
Reading time
1 min read

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:

Text

$('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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC