views:

106

answers:

1

I have a <select> with a number of <option>s. Each has a unique value. I need to disable an <option> with a given defined value (not innerhtml).

Anyone have an idea how?

+3  A: 

Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// 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='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

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

​ Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". 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");
  }
});
Jonathan Sampson
No, with the value, you would use $("option[value=someval]"). He's looking for the value, not the text inside.
Kyle Butt
Ah, good point, @KyleButt. I've updated my solution. Thank you for pointing that out.
Jonathan Sampson
Neither work in IE.
Roatin Marth
Disabling the options with “stackoverflow” doesn’t imply to enable those without “stackoverflow”.
Gumbo
@Gumbo: Correct. I was trying anticipate future problems, but I can see how my solution would cause more problems, such as if the user had *other* options disabled by default. I've updated my solution. Thanks for pointing out my error.
Jonathan Sampson