How to disable some of the options in an HTML select using jQuery
Wednesday, April 15th, 2009Sometimes you don't need users to select some of the options in the HTML drop down menu.
For example you have a dropdown menu with these options.
==========================
Please select a province/state for US/Canada
Canada
--------------
Prov1
...
Prov10
United States
--------------
State1
...
State50
==========================
What we need is a province/state but what if the user selects the separators '----' ? or the country name ?
To solve this challenge we use negative values for values that should not be selected. Then using jQuery we disable them.
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#acc_info select option").each(function (index, obj) {
// Disable items that have a value less then 0 OR an empty string
// We want those elementes to be disabled only.
if (jQuery(obj).val() == '' || jQuery(obj).val() <= 0) {
jQuery(obj).attr("disabled", "disabled");
}
});
});
</script>
Related:
