Paul McFedries' Web Home


Using JavaScript to Disable Form Controls

JavaScript doesn't have any method for disabling a control. However, I figured out a way to get more or less the same effect. Here's a simple form that contains a check box and a text box. Unless the check box is activated, you won't be able to enter anything into the text box. (Note that this method works imperfectly in Netscape 3, for some reason.)

Activate this check box and then enter your name below

Name:


Here's the form code and the required JavaScript code:

<FORM>
<INPUT TYPE=CHECKBOX NAME="CheckThis">
Activate this check box and then enter your name below
<P>
Name: 
<INPUT TYPE=TEXT NAME="UserName" onFocus="CheckCheckBox(this.form)">
</FORM>

<SCRIPT LANGUAGE="JavaScript">
<!--
function CheckCheckBox(frm)
    {
    if (!frm.CheckThis.checked)
        frm.CheckThis.focus()
    }
//-->
</SCRIPT>

If the check box is unchecked and you attempt to move into the text box, the browser won't let you do it. Instead, it just moves you back ("sets the focus" in programmer parlance) to the check box. The text box is, therefore, essentially disabled until the check box is activated.

The way it works is that the text box uses the "onFocus" event, which fires whenever you try to go into the text box. This then calls the "CheckCheckBox()" function. This function tests to see if the check box isn't checked. If it's not, the focus is set back to the check box.


Copyright © 1995-2008 Paul McFedries and Logophilia Limited