Disable Form Fields

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 the 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 stop our 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"/>

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:

myform.tx.disabled = true;
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.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow