naman
naman

Reputation: 52

How can we run If else statement inside JQuery Append Function.?

This is my append function i want to run the if else statement inside this. The data is coming in the json format.

$('#allproduct')
   .append('
    <div class="add-to-cart">'+if(item.quantity >0){+'<a class="item'+item.id+'" title="Add to Cart" href="javascript:void(0)">
    Add to Cart
    </a>'+}else{+'
   a class="item'+item.id+'" title="Add to Cart" href="javascript:void(0)">
   SOLD OUT
    </a>'+}+'
    </div>');

Upvotes: 1

Views: 9511

Answers (2)

Alexandru Severin
Alexandru Severin

Reputation: 6228

You could just declare a html variable, build it however you want then pass it to the append function.

However, if you insist on using an if condition inside the buildup of the string, you could use ternary condition as:

.append('< some html >' +
        (item.quality > 0 ? 'a possibility' : 'another possibility') +
        '</some html>');

where <some html> will contain a possibility if quality>0 and another possibility if condition is false

Adapted to your case:

$('#allproduct').append(
   '<div class="add-to-cart">'+
   ( item.quantity >0 ? 
        '<a class="item'+item.id+'" title="Add to Cart" href="javascript:void(0)">
             'Add to Cart' +
        '</a>' 
   :
        '<a class="item'+item.id+'" title="Add to Cart" href="javascript:void(0)">
             'SOLD OUT' +
        '</a>' 
    ) +
</div>');

Upvotes: 7

John Bupit
John Bupit

Reputation: 10618

You can build the HTML string first, and then append:

var htmlStr = '...';
if(condition) htmlStr += '...';
...

$('#allproduct').append(htmlStr);

Upvotes: 1

Related Questions