[SalesForce] Change color of custom button based on field value

I am trying to do the same thing as this question (set the color of a custom detail page button):

Changing the color of a custom button

but I want the set the value based on the value of a field in record.

IF value is false, set button to red, else set button to green. Not sure the proper way to use IF statements with REQUIRESCRIPT (or if this is even possible….)

I tried the following code and it does not work as expected:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 

// identify the record 
var c = new sforce.SObject("Case"); 
c.id = "{!Case.Id}"; 

IF (!c.test-ajc__c, '{!REQUIRESCRIPT("data:application/javascript;base64,KGZ1bmN0aW9uKCkgewogIHZhciBidXR0b24gPSBkb2N1bWVudC5nZXRFbGVtZW50c0J5TmFtZSgndGVzdGFqYycpWzBdOwogIGJ1dHRvbi5zdHlsZS5iYWNrZ3JvdW5kID0gJyNGRTJFMkUnOwp9KCkpOw==")}', {!REQUIRESCRIPT("data:application/javascript;base64,KGZ1bmN0aW9uKCkgewogIHZhciBidXR0b24gPSBkb2N1bWVudC5nZXRFbGVtZW50c0J5TmFtZSgndGVzdGFqYycpWzBdOwogIGJ1dHRvbi5zdHlsZS5iYWNrZ3JvdW5kID0gJyMwMURGMDEnOwp9KCkpOw==")}')

// make the field change 
c.test-ajc__c = "TRUE"; 

// save the change 
sforce.connection.update([c]); 

//refresh the page 
window.location.reload();

Any suggestions on how I might get this to work?

Adding the non-encoded code:

(function() {
  var button = document.getElementsByName('testajc')[0];
  button.style.background = '#01DF01';
}());

The other encoding is the same code as above, just with a different color.

Either of the encodings work fine if I take out the IF statement and just put the REQUIRESCRIPT with the encoding at the top of the code (removing the basic REQUIRESCRIPT at the top).

With the IF statement in place, the button is green regardless of the value of the test-ajc field. Also, clicking on the button caused the following error to occur:

A problem with the OnClick JavaScript for this button or link was
encountered:

Unexpected token ILLEGAL

Best Answer

First off, interesting use of REQUIRESCRIPT and base64 encoding! Here's a couple of things to note:

Anything inside bang-brackets is evaluated at page load time, everything else is only evaluated once your button is clicked. Here's some code I cooked up to disable a button named "test button" if the complaint field is set to true on my case.

{!IF(Case.Complaint__c = false, REQUIRESCRIPT("data:application/javascript;base64,Y29uc29sZS5sb2coJ3N1Y2Nlc3NmdWwgbG9hZCcpOw0KdmFyIGVsbXMgPSBkb2N1bWVudC5nZXRFbGVtZW50c0J5TmFtZSgndGVzdGJ1dHRvbicpOw0KZWxtc1swXS5kaXNhYmxlZCA9IHRydWU7DQplbG1zWzBdLmNsYXNzTmFtZSA9ICdidG5EaXNhYmxlZCc7"),"")}

Just make sure you get your full statement for setting the color of your button inside of bang-brackets and it'll run at load time.