Categories: Snippets

How can I disable an option in a select box based on its value in JavaScript?

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='optionvalue']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='optionvalue']").attr("disabled", "disabled");

Note that this is not case insensitive. “optionvalue” will not equal “optionvalue”. To get a case-insensitive match, you’d have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

 

Share

Recent Posts

Selecting Elements in jQuery (jQuery Selectors)

To collect a group of elements, we pass the selector to the jQuery function using…

5 years ago

jQuery library Introduction

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is…

5 years ago

Adjust li width fit with ul width of the outer div/body

HTML:- [crayon-662e77ff66074635071334/] CSS:- [crayon-662e77ff6607a395092562/] JavaScript:- [crayon-662e77ff6607d989253738/]  

5 years ago

Customize Input Box using jQuery

Prevent users typing special characters in text box, textarea, etc. [crayon-662e77ff661b1755049178/] ^[a-zA-Z]+$ Alphabets ^[a-zA-Z\s]+$ Alphabets…

5 years ago

JavaScript simple form validation with example

Any interactive web site has form input - a place where the users input different…

5 years ago

Clear the browser cache of CSS or JavaScript Using Javascript

[crayon-662e77ff6650f766106319/]  

5 years ago