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);
};
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
trueorfalse.nullis falsy, and strings with content are truthy. That means:You can use other kinds of expressions too, like a ternary expression or the logical OR operator:
In this case, logical OR is our most interesting choice. When you use the operator, the following happens:
In the above example,
aisnull, so it is falsy. The expression returns the right side, the value ofb. So we can take advantage of this behavior by writingvarFirstName || '', which will either return the first name (if there is one), or if it’s null, the right side gives us an empty string.I added a call to
trimto remove extra spaces from the result.