Disabling Form Elements


f.elements["password"].disabled = true; 

Sometimes, form elements should not be modifiable. The following scenarios are just some examples:

  • Form elements "abused" just to display data, such as long license agreements packed into a <textarea> field

  • Elements being activated or deactivated upon user interaction

  • Data in form elements being "locked" when the form is being submitted

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)

<script language="JavaScript"   type="text/javascript"> function enable(f) {   f.elements["password"].disabled = false; } function disable(f) {   f.elements["password"].disabled = true; } </script> <form>   <input type="radio" name="radiobutton"     value="login"checked="checked"     onclick="enable(this.form);" />Login   <input type="radio" name="radiobutton"     value="register"     onclick="disable(this.form);" />Register<br />   Username <input type="text" name="username" />   <br />   Password <input type="password"     name="password" /><br /> </form> 

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)

function enable(f) {   f.elements["password"].readOnly = false; } function disable(f) {   f.elements["password"].readOnly = true; } 

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!





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net