faqts : Computers : Programming : Languages : JavaScript : Forms : Buttons

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

417 of 570 people (73%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I disable a button?

Sep 24th, 2001 13:32
Deion, Martin Honnen,


With IE4+ and NN6 you can set
  buttonReference.disabled = true
to disable (button gets greyed out and unclickable) and
  buttonReference.disabled = false
to enable back.
With older browsers all you can do is temporarily disable the onclick 
handler by storing it and setting it to null for disabling and 
restoring it for enabling. NN3/4 on windows also allow to change the 
button face to something indicating the button is 'DISABLED'.
Here is the complete code with examples:

<HTML>
<HEAD>
<SCRIPT>
function disableButton (button) {
  if (document.all || document.getElementById)
    button.disabled = true;
  else if (button) {
    button.oldOnClick = button.onclick;
    button.onclick = null;
    button.oldValue = button.value;
    button.value = 'DISABLED';
  }
}
function enableButton (button) {
  if (document.all || document.getElementById)
    button.disabled = false;
  else if (button) {
    button.onclick = button.oldOnClick;
    button.value = button.oldValue;
  }
}
</SCRIPT>
</HEAD>
<BODY>

<FORM NAME="formName">
<INPUT TYPE="button" NAME="aButton" VALUE="praise GOD"
       ONCLICK="alert('Hail thee, Kibo');"
>
<A HREF="javascript: disableButton(document.formName.aButton); void 0">
disable
</A>
|
<A HREF="javascript: enableButton(document.formName.aButton); void 0">
enable
</A>
<BR>
<BUTTON NAME="a2ndButton" 
        ONCLICK="alert('Visit JavaScript.FAQTs.com');"
        STYLE="background-color: orange; color: white; font-size: 18pt;"
>
JavaScript Knowledge Base
</BUTTON>
<A HREF="javascript: disableButton(document.formName.a2ndButton); void 
0">
disable
</A>
|
<A HREF="javascript: enableButton(document.formName.a2ndButton); void 
0">
enable
</A>
</FORM>
</BODY>
</HTML>

** Quick Note from DeionXxX ***: That code breaks if you click the 
disable button more than once in NN4... to fix that edit the 'else if 
(button)' in the disable function to 'else if(button && button.value != 
'DISABLED')'  that should fix that error.