1. Technology
Send to a Friend via Email

Disable Form Fields

clr gif
Join the Discussion

Questions? Comments?

Sometimes when you have a form for your visitor to fill out you have an input field that should only be enterable if certain other fields are entered or selected.We can of course check for this when we validate te field but wouldn't it be useful to be able to stop our visitor from entering anything in the field until after they have entered or selected the appropriate values that allow the field to be entered.

We could hide the field until the criteria is met but that will stopour visitor from knowing that the field even exists and will stop those with Javascript disabled from being able to enter a value in the field even if it is allowed. Better if we can show the field but not allow any input.

Here is a form where the text input field is disabled until the preceding checkbox is selected.

Here is the code that I used to create the form.

<form name="myform" action="#">
<input type="checkbox" name="cb" onchange="chgtx();" />
<input type="text" length="10" name="tx" />
</form>

We use the disabled attribute to protect the field from being entered. We set it when the page finishes loading and then unset it and set it again as the checkbox is selected or unselected. Here is the code to produce the effect:

function start() {
myform.tx.disabled = true;
}
onload = start;
function chgtx() {
myform.tx.disabled = !myform.cb.checked;
}

The first function disables the field after the page finishes loading. We could disable the field in the HTML but that would stop anyone with Javascript disabled from ever being able to enter anything in the field. The second function sets the disabled state for the field to be the opposite of the checked state for the checkbox.

Note that disabled fields are not as easy to identify in Internet Explorer as they are in other browsers as IE just stops the field from being enterable while other browsers also change the appearance of the field to show that it is disabled.

Note that this code works with IE4+ , Netscape 6+, Mozilla, Firefox, and Opera 6+. It will have no effect in earlier browsers.

©2014 About.com. All rights reserved.