When developing forms for the web, there are two methods to make a form element non-editable – using either the “readonly” or “disabled” attributes. Each method has its benefits and drawbacks, however there is a workaround available to combine the best of both worlds.
The more common of the two methods is to use the “disabled” HTML attribute. The canonical syntax for applying it to a textbox would be as follows:
<input type="text" disabled="disabled" />
This attribute will effectively prevent the user from making changes to the textbox, and also change the color of the box to a dark gray so that users intuitively understand that they cannot make changes to it. The disabled form elements do have a drawback though; they will not be submitted back to the form during a GET or POST operation. This means that disabled elements completely disappear.
For simpler applications, the loss of disabled elements from the HTML header does not pose a problem. However, for more complex applications, such as apps that might utilize dynamic form elements with automated binding; the code can often be more elegantly implemented if the disabled elements are visible in the post-back.
The alternative to the “disabled” attribute is the “readonly” attribute. This would be implemented as follows:
<input type="text" readonly="readonly" />
This will indeed make the element read-only, and the element will show in post-back. The challenge with the “readonly” attribute, on the other hand, is that it does not provide user interface cues that the element is actually read-only. The textbox will display similar to editable textboxes, and confuse users when they try to enter text.
The solution to these issues is relatively simple. Using CSS styles, a “readonly” textbox can be made to look “disabled”, combining the best of both worlds. The style would be written similar to the following:
border:1px solid #888;
Notice the additional padding – overriding the borders in some browsers will remove the 3D effect, and result in the appearance of less horizontal space. Additional horizontal padding will help remedy that effect.
Finally, just apply that CSS class to the input element:
<input type=”text” readonly=”readonly” class=”xreadonly” />
This solution is language agnostic, and offers an effective workaround for most web development frameworks.
Written by Andrew Palczewski
About the Author
Andrew Palczewski is CEO of apHarmony, a Chicago software development company. He holds a Master's degree in Computer Engineering from the University of Illinois at Urbana-Champaign and has over ten years' experience in managing development of software projects.