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.
The disabled attribute can be set to keep a user from selecting the option until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript is required to remove the disabled value, and make the option selectable.
To disable any item, just need to add attribute "disabled" with value "disabled" to the list item.
To change the selected option in an HTML <select> element we have to change the value property on the <select> element or the selected property on the <option> element we want to get selected. There are different ways we can do it and choosing one or another will depend on the information we have available to us.
The disabled attribute for <select> element in HTML is used to specify that the select element is disabled. A disabled drop-down list is un-clickable and unusable. It is a boolean attribute.
With your current markup this will work:
$("select option:contains('Value b')").attr("disabled","disabled");
http://jsfiddle.net/CtqC6/
EDIT
http://jsfiddle.net/CtqC6/1/
var variable = "b"
$("select option:contains('Value " + variable + "')").attr("disabled","disabled");
$("select").prop("selectedIndex",-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With