Sometimes, form elements should not be modifiable. The following scenarios are just some examples:
JavaScript offers several options to achieve this effect. Every form element supports the disabled property. When it's set to true, the form element grays out and cannot be modified any longer. In the following listing, this is shown using a simple login form. This form can also be used for registering a user; when a user wants to register, no password is required. Therefore, the password field must gray out when the form switches into registration mode: Disabling Form Elements (disabled.html)
In Figure 8.4, the effect of this code can be seen: the text field grays out when the Register radio button is selected. Figure 8.4. The password field is now disabled.Sometimes, the graying-out effect is not desired. An alternative way to disable a form element comes via its readOnly JavaScript property. When this property is set to TRue, the form field does not change its appearance, but cannot be changed any longer. Here is the code that implements this: Making Form Elements Read-Only (readonly.html; excerpt)
Note In older browsers, another simple trick was used to make text fields in particular read-only. After the field got the focus, it was removed immediately: <input type="text" onfocus="this.blur();" /> Warning Even though you can use JavaScript to disable a form field or make it read-only, you should be aware that JavaScript can be easily deactivated and an HTTP request can be trivially forged, as well. So do not rely on this JavaScript effect but always validate your data on the server side! |