According to HTML specs, the select
tag in HTML doesn\'t have a readonly
attribute, only a disabled
attribute. So if you want to keep
Simple jQuery solution
Use this if your selects have the readonly
class
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
Or this if your selects have the readonly="readonly"
attribute
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
One simple server-side approach is to remove all the options except the one that you want to be selected. Thus, in Zend Framework 1.12, if $element is a Zend_Form_Element_Select:
$value = $element->getValue();
$options = $element->getAttrib('options');
$sole_option = array($value => $options[$value]);
$element->setAttrib('options', $sole_option);
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
Edit: With Internet Explorer, you also need this JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
You can re-enable the select object on submit.
EDIT: i.e., normally disabling the select tag (with the disabled attribute) and then re-enabling it automatically just before submiting the form:
Example with jQuery:
To disable it:
$('#yourSelect').prop('disabled', true);
To re-enable it before submission so that GET / POST data is included:
$('#yourForm').on('submit', function() {
$('#yourSelect').prop('disabled', false);
});
In addition, you could re-enable every disabled input or select:
$('#yourForm').on('submit', function() {
$('input, select').prop('disabled', false);
});
If the select dropdown is read-only since birth and does not need to change at all, perhaps you should use another control instead? Like a simple <div>
(plus hidden form field) or an <input type="text">
?
Added: If the dropdown is not read-only all the time and JavaScript is used to enable/disable it, then this is still a solution - just modify the DOM on-the-fly.
html solution:
<select onfocus="this.blur();">
javascript ones:
selectElement.addEventListener("focus", selectElement.blur, true);
selectElement.attachEvent("focus", selectElement.blur); //thanks, IE
to remove:
selectElement.removeEventListener("focus", selectElement.blur, true);
selectElement.detachEvent("focus", selectElement.blur); //thanks, IE
edit: added remove methods