You can dynamically apply a selection rule in a SELECT element.
For example, you can limit the selection to the currently selected value or limit the options that the user can select.
Check out the live demo :
HTML
<select id="selectElement"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> <option value="7">Option 7</option> </select> <select id="restrictOptions"> <option value="">Do not restrict options</option> <option value="3,4,6,7">Restrict options to 1, 2 and 5</option> <option value="1,2,7">Restrict options to 3 to 6</option> <option value="other">Restrict to currently selected option</option> </select>
Javascript
function applySelectRule(selector, rule) { var el = $(selector); var currentValue = el.val(); var valuesRestricted = (rule == 'other' ? '' : rule).split(RegExp('\\s*,\\s*')); el.unbind('change.restrictedRule') // remove old binding .bind('change.restrictedRule', function() { if (rule == 'other') { if (el.val() != currentValue) el.val(currentValue); } }).find('option').each(function() { var opt = $(this); if (valuesRestricted.indexOf(opt.val()) == -1) { opt.removeAttr('disabled'); } else { opt.attr('disabled', true); } }).end().find('option[value="'+currentValue+'"]:disabled').each(function() { // set first value that is not disabled el.val(el.find('option:not(disabled)').text()); }); }; $('#restrictOptions').change(function() { applySelectRule('#selectElement', $(this).val()); });
The code should be clear enough, however I can refine it if you need to.
source share