jQuery Disable Select Option Based on Value

jQuery Disable Select Option Based on Value

If you are working with a select dropdown option box. And want to disable the selection based on the dropdown value.

So, in this tutorial, you will learn how to disable select options based on their selection values using jQuery.

jQuery Disable Select Option Based on Value

You can use the following steps and disable the select option based on the value using jQuery:

  • Step 1: Include jQuery Library
  • Step 2: HTML Select Element
  • Step 3: jQuery Code

Step 1: Include jQuery Library

First, make sure you have the jQuery library included in your HTML file. You can include it by adding the following line within the <head> section of your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Step 2: HTML Select Element

Create a <select> element in your HTML file with multiple <option> elements. Each <option> should have a value attribute that you can use to identify it.

<select id="mySelect">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

Step 3: jQuery Code

Use the following jQuery code to disable select dropdown options based on their values:

$(document).ready(function() {
  $('#mySelect').change(function() {
    var selectedValue = $(this).val();
    disableOptions(selectedValue);
  });

  function disableOptions(value) {
    $('#mySelect option').each(function() {
      if ($(this).val() === value) {
        $(this).prop('disabled', true);
      } else {
        $(this).prop('disabled', false);
      }
    });
  }
});

Save the above given HTML and jquery code in your file and open it in a web browser. Now, whenever you select an option from the dropdown, that option will be disabled, preventing it from being selected again.

Conclusion

That’s it! You’ve successfully learned how to disable select options based on their values using jQuery.

Recommended Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *