Search code examples
jqueryhtmlselectdisabled-input

jQuery - disable select option based on option keyword not by value


I have this HTML select code:

​<select name="loc_code">
  <option value="">Select</option>
  <option value="loc1">Loc1 status ON</option>
  <option value="loc2">Loc2 status ON</option>
  <option value="loc3">Loc3 status OFF</option>
  <option value="loc4">Loc4 status ON</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

So, I have a problem disabling option drop downs based on the text name not by value. I need to disable only options that contains status OFF.

I tried to modify this jQuery code from other posted similar questions on StackOverflow, but obviously it is wrong:

$("select[name="loc_code"] option:selected").text(function() {
  var $thisOption = $(this);
  var valueToCompare = "OFF";

  if($thisOption.val() == valueToCompare) {
    $thisOption.attr("disabled", "disabled");
  }
});​

Any help is greatly appreciated.


Solution

  • Why not do:

    $('select[name=loc_code] option').each(function() {
        if ($(this).text().indexOf('OFF') >= 0) $(this).attr('disabled', 'disabled');
    });​
    

    jsFiddle example