CSharpNewBee
CSharpNewBee

Reputation: 1981

if statement inside $.each, Jquery

I'm building some html based on JSON data returned from a WebMethod. I need to know how to leave out certain

elements, based on if a particualr value is present or not. I've got this, so far but, i get syntax error within VS

$.each(amlData, function (index, item) {
    $('<div class=message><pre><dl><dt>Matched On:</dt><dd>' + item.ItemType +
    '</dd><dt>Date Listed:</dt><dd>' + item.DateListed +
    '</dd><dt>ID:<dt><dd>' + item.ID +
    '</dd><dt>Percentage:</dt><dd>' + item.PercentageMatch +
    '</dd><dt>List:</dt><dd>' + item.List +
    '</dd>' if(item.Gender != null) { + '<dt>Gender:</dt><dd>' + item.Gender   } +  '</dl></pre></div>').appendTo('div#results');                                  
});

Upvotes: 1

Views: 4909

Answers (4)

Jatin patil
Jatin patil

Reputation: 4288

Try,


    var result = "";
    $.each(amlData, function (index, item) {
        result  = "Your Initial String"; 
        if(item.Gender != null) {
            result = result +  "" + item.Gender; // append string based on your condition
         }
     });
    $(result).appendTo('div#results');

Upvotes: 0

marteljn
marteljn

Reputation: 6516

An if statement won't work in this context but a ternary operator will:

'</dd>'  + ((item.Gender != null) ? '<dt>Gender:</dt><dd>' + item.Gender + '</dd>' : '<dd></dd>') + '</dl></pre></div>').appendTo('div#results')

Upvotes: 4

Adam Marshall
Adam Marshall

Reputation: 3009

The problem is where you have an if statement in line, where it would expect a string. Try:

$.each(amlData, function (index, item) {
                      $('<div class=message><pre><dl><dt>Matched On:</dt><dd>' + item.ItemType +
                          '</dd><dt>Date Listed:</dt><dd>' + item.DateListed +
                          '</dd><dt>ID:<dt><dd>' + item.ID +
                          '</dd><dt>Percentage:</dt><dd>' + item.PercentageMatch +
                          '</dd><dt>List:</dt><dd>' + item.List +
                          '</dd>' + ((item.Gender != null) ? '<dt>Gender:</dt><dd>' + item.Gender : '') +  '</dl></pre></div>').appendTo('div#results');

                  });

Upvotes: 1

x4rf41
x4rf41

Reputation: 5337

you cant use if like that. but you can do this:

'</dd>' + (item.Gender != null ? '<dt>Gender:</dt><dd>'+item.Gender : '')+  '</dl>...

Upvotes: 3

Related Questions