Lauren
Lauren

Reputation: 33

New to JavaScript, how to do a null check?

I am trying to learn JavaScript. First day! I want to concatenate the First and Last names. This is what I have so far. It works fine, but if I don't enter one of the fields, it just shows up as null. How do I avoid that? Where would I put that clause in the following code? Thanks for your help in advance!

function ShowFullName()
{
    var varFirstName = Xrm.Page.getAttribute("lauren_firstname").getValue();
    var varLastName = Xrm.Page.getAttribute("lauren_lastname").getValue();
    Xrm.Page.getAttribute("lauren_name").setValue(varFirstName + " "  + varLastName);
};

Upvotes: 3

Views: 2627

Answers (3)

josh3736
josh3736

Reputation: 144822

You can take advantage of the fact that all variables are truthy or falsy in JavaScript. In other words, every variable can be coerced (converted) into true or false.

null is falsy, and strings with content are truthy. That means:

var a = null;
var b = 'hello';

if (a) {
    // does not run
} else {
    // runs
}

if (b) {
    // runs
}

You can use other kinds of expressions too, like a ternary expression or the logical OR operator:

alert(a ? 'yes' : 'no'); // => no
alert(b ? 'yes' : 'no'); // => yes

alert(a || b); // => hello

In this case, logical OR is our most interesting choice. When you use the operator, the following happens:

  1. If the left side evaluates truthy, return that value.
  2. Otherwise, return the value that the right side evalutes to.

In the above example, a is null, so it is falsy. The expression returns the right side, the value of b. So we can take advantage of this behavior by writing varFirstName || '', which will either return the first name (if there is one), or if it's null, the right side gives us an empty string.

function ShowFullName() {
    var varFirstName = Xrm.Page.getAttribute("lauren_firstname").getValue();
    var varLastName = Xrm.Page.getAttribute("lauren_lastname").getValue();

    Xrm.Page.getAttribute("lauren_name").setValue(((varFirstName || '') + " " + (varLastName || '')).trim());
}

I added a call to trim to remove extra spaces from the result.

Upvotes: 3

Jeff Robert Dagala
Jeff Robert Dagala

Reputation: 633

try this:

function ShowFullName()
    var varFirstName = Xrm.Page.getAttribute("lauren_firstname").getValue();
    var varLastName = Xrm.Page.getAttribute("lauren_lastname").getValue();

    if(varFirstName == null || varFirstName.ToLower() == "null") { 
        varFirstName = "";
    }

    if(varLastName == null || varLastName.ToLower() == "null") { 
        varLastName = "";
    }

    Xrm.Page.getAttribute("lauren_name").setValue(varFirstName + " "  + varLastName);
};

Upvotes: 1

Darren Wainwright
Darren Wainwright

Reputation: 30727

You can check if something is null like:

if (obj == null) { 
  // do this 

}

so something like

if (varFirstName == null) { varFirstname = "";}

This will set firstName to an empty string

Upvotes: 1

Related Questions