This section describes the technical tricks you can use in onClick JavaScript buttons attached to standard Objects or Custom Objects..

Disabling Buttons After A Click

Did you ever have the problem of clicking a button and the form appears to freeze before doing the action? Sometimes this creates a problem. The solution is to disable the button after the user has clicked on it. Sounds simple enough…except that you don’t have direct access to the HTML on the page. The good news is that we still have access to the HTML elements. Knowing the name of the control is easy. JavaScript provides a function for retrieving an object in the form of getElementsByTagName(). This function returns a list of all the requested objects. So using a for loop we can iterate through the returned list and check the Text (in the .value property) to see if this is the button we are looking for.

// disable the button
var inputList = document.getElementsByTagName('input');
var ele;
var oldClass;

for(var i=0; i < inputList.length; i++)
{
   if(inputList[i].value.indexOf('New Quote') != -1)
   {
      ele = inputList[i];
      break;
   }
}

if( ele != NaN )
{
   ele.disabled = true;
}

If you paste the above code into a custom button when you click it the button will become disabled. In some cases though if you open a popup window or something else the user might move the window around and try to click your button again. Sound strange? Well not really because while the .disabled property is set to true, the appearance of the button doesn’t change. Salesforce uses their own class styles. After a bit of digging I found the style needed. .classname = “btnDisabled”. Before we can set it, we need to save the original button class so we can reset it later when we enable the button.

oldClass = ele.className;
ele.className = "btnDisabled";

Now the button appears disabled. Finally to re-enable the button we set .disabled = false and reset the class. This is what the entire function should look like when you’re done:

// disable the button
var inputList = document.getElementsByTagName('input');
var ele;
var oldClass;

for(var i=0; i < inputList.length; i++)
{
   //alert('name = ' + inputList[i].value);
   if(inputList[i].value.indexOf('New Quote') != -1)
   {
      ele = inputList[i];
      break;
    }
}

if( ele != NaN )
   ele.disabled = true;

oldClass = ele.className;
ele.className = "btnDisabled";

// your other javascript code

ele.disabled = false;
ele.className = oldClass;

[contact-form]
Filed under: Salesforce.com Programming