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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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