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 the user from changing the dropdown, you have to use disabled
.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly
attribute for a select
tag, and still get the POST data?
I know that it is far too late, but it can be done with simple CSS:
The style hides all the options and the groups when the select is in
readonly
state, so the user can not change his selection.No JavaScript hacks needed.
This is the best solution I have found:
The code above disables all other options not selected while keeping the selected option enabled. Doing so the selected option will make it into the post-back data.
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
JS:
HTML:
Edit: With Internet Explorer, you also need this JS:
What I found works great, with plain javascript (ie: no JQuery library required), is to change the innerHTML of the
<select>
tag to the desired single remaining value.Before:
Sample Javascript:
After:
This way, no visiual effect change, and this will POST/GET within the
<FORM>
.If you disable a form field, this won't be send when form is submitted. So if you need a
readonly
that works likedisabled
but sending values do this :After any change in readonly properties of an element.
In IE I was able to defeat the onfocus=>onblur approach by double-clicking. But remembering the value and then restoring it in the onchange event seems to handle that issue.
You can do similar without expando properties by using a javascript variable.