October 30, 1999 - Disabling Form Elements | WebReference

October 30, 1999 - Disabling Form Elements

Yehuda Shiran October 30, 1999
Disabling Form Elements
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

HTML 4 adds the DISABLED attribute to form elements. For example:

<INPUT TYPE="button" NAME="myButton" VALUE="Submit" DISABLED>

This attribute can be attached to any <INPUT> tag. It disables the specified form element (it cannot be clicked). Note that this attribute is currently only supported by Internet Explorer 4.0x and above. A disabled form element can be enabled via JavaScript:

document.formName.elementName.disabled = false;

The element's disabled property holds a Boolean value (true or false). The following statement toggles the state of a form element:

document.formName.elementName.disabled = !document.formName.elementName.disabled;

The following code creates a form with a single text box. When the value of this field appears to be an emaill address, the submit button is enabled:

var IE4 = (document.all) ? 1 : 0;
if (IE4)
  var timerID = setInterval("enableSubmit()", 200);
function enableSubmit() {
  if (!IE4) return;
  var form = document.newsletter;
  var currentState = form.sub.disabled;
  var newState = !isEmail(form.email.value);
  if (newState != currentState)
    form.sub.disabled = newState;
function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
// -->
<FORM NAME="newsletter">
<INPUT TYPE="text" NAME="email" SIZE="30" onKeyUp="enableSubmit()">
<INPUT TYPE="submit" NAME="sub" VALUE="Submit" DISABLED>

If you study this code carefully, you'll notice that we're always (every 200 milliseconds, or 0.2 seconds) checking the value of the text field to see if it matches the syntax of an email address. If it looks like an email address, we enable the button so that the form can be submitted. If it doesn't represent an email address, we disable the button (if it is currently enabled). We also evaluate the text whenever the user presses a keyboard button in the box. The 200 millisecond interval is required because the user might enter an email address without pressing a button (e.g., pasting a string in the box). Now take a look at a live example that lets you subscribe to Webreference's newsletter:

HTML (daily)
Text (weekly)
Don't forget to check out Microsoft's documentation for the DISABLED attribute and the disabled property.