mafortis
mafortis

Reputation: 7128

Ajax check value of data

I'm getting data as JSON response and each time one of my fields is empty and one has value so I need to make if statement to check which one has value and print that one.

So far I tried:

if(data.longtext_dec != ''){
  var ress = data.longtext_dec;
} else {
  var ress = data.text_dec;
}

and

if($.trim(data.longtext_dec) === '')
{
  var ress = data.longtext_dec;
} else {
  var ress = data.text_dec;
}

each time the code keeps printing longtext_dec or show both as null.

So I need help to get this right, the result of this ress I want to append it in my view (either this or that).

How can I fix this code?

UPDATE

network response tab:

product_id        15
specification_id  5
text_dec          ddd
longtext_dec      null
id                69

payload

{"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}

Upvotes: 0

Views: 94

Answers (4)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Try this :

var data = {"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69};

var ress;

(data.longtext_dec !== null) ? ress = data.longtext_dec : ress = data.text_dec;

console.log(ress);

Upvotes: 0

Rajnikant
Rajnikant

Reputation: 2236

you can leverage javascript || operator as below

var res = data.longtext_dec || data.text_dec;

Upvotes: 0

Atanas Antonov
Atanas Antonov

Reputation: 36

There is a difference between empty string, null, undefined and boolean true/false. As shown in the JSON you want to check if the value from the response object is null. So just check

if( data.longtext_dec !== null ) 

Here is very well explained:

https://stackoverflow.com/a/27550756/3868104

Optional you can check for whatever you want for example:

if( data.longtext_dec !== "" )

and so on.

Upvotes: 0

Dan Nagle
Dan Nagle

Reputation: 5425

Just use if (data.longtext_desc) it's a way to check if data variable evaluates to true. undefined, null, false, 0, an empty string evaluates to false.

    var ress; // undefined
    if (data.longtext_desc) {
      ress = data.longtext_desc;
    } else {
      ress = data.text_dec;
    }

Optionally use a ternary operator:

    var ress = data.longtext_desc ? data.longtext_desc : data.text_dec;

Upvotes: 1

Related Questions