Reputation: 705
I need to disable a select option based on the value of a variable. The value is similar to one of the select option value and it needs to be disabled.
For ex,
<select>
<option>Value a</option>
<option>Value b</option>
</select>
$variable = <some select option value>;
So if variable is equal to Value a then it needs to be disabled in select option.
Thanks.
Upvotes: 22
Views: 85658
Reputation: 25766
$("select option[value='"+ $variable + "']").attr('disabled', true);
Upvotes: 28
Reputation: 7166
This should be a faster solution
$('select').children('option[value="' + $variable + '"]').attr('disabled', true)
Upvotes: 10
Reputation: 78520
With your current markup this will work:
$("select option:contains('Value b')").attr("disabled","disabled");
EDIT
var variable = "b"
$("select option:contains('Value " + variable + "')").attr("disabled","disabled");
$("select").prop("selectedIndex",-1)
Upvotes: 33
Reputation: 72222
Let's say you had the following markup
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Using this jQuery, the saab option would be disabled.
$("select option").each(function() {
var $thisOption = $(this);
var valueToCompare = "saab";
if($thisOption.val() == valueToCompare) {
$thisOption.attr("disabled", "disabled");
}
});
Upvotes: 7