faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

388 of 459 people (85%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How to disable a text field/text area?

Feb 25th, 2000 07:49
Martin Honnen,


With IE4/5 and NN6 you can set the
  disabled
property, with older browsers you can set the onfocus handler to blur 
so that the field is at least not editable.

<HTML>
<HEAD>
<STYLE>
</STYLE>
<SCRIPT>
function skip () { this.blur(); }
function disableTextField (field) {
  if (document.all || document.getElementById) 
    field.disabled = true;
  else {
    field.oldOnFocus = field.onfocus;
    field.onfocus = skip;
  }
}
function enableTextField (field) {
  if (document.all || document.getElementById)
    field.disabled = false;
  else {
    field.onfocus = field.oldOnFocus;
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm">
<INPUT TYPE="text" NAME="aField" VALUE="Kibology">
<INPUT TYPE="button" VALUE="disable field"
       ONCLICK="disableTextField(this.form.aField)"
>
<INPUT TYPE="button" VALUE="enable field"
       ONCLICK="enableTextField(this.form.aField)"
>
</BODY>
</HTML>

Of course if you just want to statically disable a text field you can 
use html attributes
  <INPUT TYPE="text" NAME="aField" VALUE="Kibology" DISABLED>
with IE4/5 and NN6 and you can use
  <INPUT TYPE="text" NAME="aField" VALUE="Kibology" 
         ONFOCUS="this.blur()"
  >
for older browsers. To combine both (which has the advantage of 
allowing copy/paste operations on the DISABLED text field with IE4/5 
and NN6 use

  <INPUT TYPE="text" NAME="aField" VALUE="Kibology" DISABLED 
         ONFOCUS="if (!document.all && !document.getElementById) 
this.blur()"
  >