0

Quick noobish question. Can you put if statement inside jQuery append function?

I have this code

$('table#dataTable tbody').append('<tr>
<td class="success">'+json.forms[i].name+'</td><td>'+json.forms[i].category+'</td>
</tr>');

And i would like to add an if statement to the second <td></td> like if(something === x){ do it)else{don't do it}; and then continue with append.

z0mbieKale
  • 969
  • 1
  • 14
  • 44

1 Answers1

2

Simply do the concatenation outside the append

var html = '<tr><td class="success">'+json.forms[i].name+'</td>'
if (something == x)
{
   html += '<td>'+json.forms[i].category+'</td>';
}
html += '</tr>';

$('#dataTable tbody').append(html);

Or use a ternary operator as @ArunPJohny said

var html = '<tr><td class="success">'+json.forms[i].name+'</td>'
html += something == x ? '<td>'+json.forms[i].category+'</td>' : '';
html += '</tr>';

$('#dataTable tbody').append(html);

Single line

var html = '<tr><td class="success">'+json.forms[i].name+'</td>' + (something == x ? '<td>'+json.forms[i].category+'</td>' : '') + '</tr>';
$('#dataTable tbody').append(html);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94