Disabling A Button

 

Sometimes, you may want to disable a button from JavaScript. You need to, for example, when the service called by the button is not available. A Web service called synchronously should not be called again while working on its previous call.

Play around with the following two buttons. Toggle the second button with the first one:

Here is how the buttons are defined:

<p><input type="button" id="b1" onClick="disableOtherButton()" value="Toggle Other Button"></p>
<p><input type="button" id="b2" disabled onClick="sayHello()" value="Say Hello"></p>

The first button toggles the disability of the button below it, through the disableOtherButton() function:

function disableOtherButton()
{
     if ( buttonForm.b2.disabled )
     {
          buttonForm.b2.disabled = false;
     }
     else
         buttonForm.b2.disabled = true;
}

Here is the whole JavaScript code:

<script language="JavaScript" type="text/javascript">
<!--
function disableOtherButton()
{
     if ( buttonForm.b2.disabled )
     {
          buttonForm.b2.disabled = false;
     }
     else
          buttonForm.b2.disabled = true;
}

function sayHello()
{
     alert("Hello there");
}
// -->
</script>