1

I have jQuery code like

      for(var j in indivudvalbookdetails) {
         if(indivudvalbookdetails[j]['status'] == "") {
          ... 
         }
     }

Now there might be some items in the loop where status field won't exists, if there are such items the code in the if condition should work.

3
  • Instead of the empty character, check for undefined, and use strict comparison operator. Commented Nov 5, 2017 at 10:04
  • can u show me in the code Commented Nov 5, 2017 at 10:08
  • This is pure javascript, theres no jquery involved here. Commented Nov 5, 2017 at 10:29

4 Answers 4

3

Try this:

var myElement =  indivudvalbookdetails[j]['status'];
if (typeof(myElement) != 'undefined' && myElement != null)
{
  // exists.
}

You can also try with JQuery like:

if ($('#elementId').length > 0) {
  // exists.
}
Sign up to request clarification or add additional context in comments.

Comments

3

Just check if its undefined:

if(typeof indivudvalbookdetails[j]['status'] === "undefined") { ...

Comments

1

Your code is comparing your variable to an empty string. But if this variable is not defined, it can’t compare it, so you can do :

if(indivudvalbookdetails[j]['status'] == undefined)

If the « status » var is defined but just empty you can do

 if(indivudvalbookdetails[j]['status'] == null)

2 Comments

Non-existing/assigned values are returned as undefined. Strict comparison is needed, if the data contains zeros or empty characters.
tldr: in most cases use ===. This is one.
1

You check like this

if(!indivudvalbookdetails[j]['status'])

2 Comments

Note that {status:""} wont pass the test
Sorry, didn't think of that. We would have to check for undefined and null as well

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.