3

I am trying to pull data from a list, but skip any that are empty. Below is the portion of my JS link that Is having this error:

var description = document.createElement("a");
description.innerHTML = item.Description;
var wTitle = document.createElement("div");
wTitle.innerHTML = item.Title;

if (item.URL !=null || item.URL != "") {
   description.setAttribute("href", item.URL);
        }

Everything works fine, except the URL field, if left blank returns will return the relative url with a "/null" on the end. If the URL field is populated, it works fine.

2
  • console.log(item.URL,typeof item.URL) in the DEV console and check what URL is Mar 16, 2016 at 19:44
  • Not sure about JS exactly but I know in .NET you'd want to use an IsNull function, which returns a boolean indicating whether data exists or not. IIRC the explanation goes something like "You can't test equality to a null value because there's nothing there to test." So in your case something like if (item.URL.IsNull == false...
    – thanby
    Mar 16, 2016 at 19:47

1 Answer 1

3

The OR(||) condition should be AND(&&) in like below lines of code:

if (item.URL !=null && item.URL != "") {
   description.setAttribute("href", item.URL);
}

Otherwise, if item.URL is null, item.URL != "" will be true and it will go inside the if statement.

EDIT: Including excellent suggestion in Anders' comment

It would be recommended to use

if(!(SP.ScriptHelpers.isNullOrUndefinedOrEmpty(item.URL))) {
   description.setAttribute("href", item.URL);
}
2
  • Also a function provided by SP that one could use: SP.ScriptHelpers.isNullOrUndefinedOrEmpty , basically the same as the answer, but also check for undefined and saves some typing. Mar 17, 2016 at 8:33
  • @AndersAune: That's an excellent suggestion, included in answer.
    – AmitWiki
    Mar 17, 2016 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.