[SalesForce] Salesforce Javascript Test for Blank Field

I'm working on an inline visualforce page that is embedded into a standard lead detail record. I'm using javascript logic on the vf page to get the value of a field and then, depending on the value retrieved, display different messages. The issue I'm a having is that I'm not able to test in the javascript whether the field is null/blank/''/"".

My code looks like:

<div id="divFDNC"></div>

    <script language="javascript">

       if(document.getElementById('divFDNC')){
          var gIE = document.all ? true:false;
          if({!Lead.Checkbox__c} == true){

            if({!Lead.Custom_Status__c} == '00' || {!Lead.Custom_Status__c} == ''){
               document.getElementById('divFDNC').innerHTML = '<font style="font-size: 11px;" class="FDNC_Message">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>MY MESSAGE</b></font>'
             }
            else{
               document.getElementById('divFDNC').innerHTML = '<font style="font-size: 11px;" class="FDNC_Message">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>MY MESSAGE 2</b></font>'
             }

The message works when I enter '00' into the Custom_Status__c field. However, when the Custom_Status__c field is blank, then it doesn't display the message like it should. I've tried the following to get it to work (no luck on any of them):

'{!Lead.Custom_Status__c}' == '' / null / NaN / undefined

"{!Lead.Custom_Status__c}" == "" / null / NaN / undefined

{!Lead.Custom_Status__c} == '' / null / NaN / undefined

Does anyone know how to properly test that a field is blank, using javascript? Thanks in advance for any help you can provide.

Best Answer

Anything that doesn't strictly evaluate to a native value should be enclosed in quotes, and you should also escape those values to avoid XSS injection attacks.

I would personally write the following code:

if({!OR(Lead.Custom_Status__c = '00', ISBLANK(Lead.Custom_Status__c))}) {

Salesforce will evaluate this to

if(true)

when the status is blank or set to 00, and

if(false)

otherwise.

Alternatively, if you want to use the value directly, make sure you use JSENCODE:

var customStatus = "{!JSENCODE(Lead.Custom_Status__c)}";
if(customStatus == "00" || !customStatus) {
Related Topic