Steve Doson
Steve Doson

Reputation: 713

How to insert conditional statements in html inside a JavaScript function?

This is my code:

var tr = `<tr>
    <td>${flippableTemplate(item['Group 1'])}</td>
    <td>${flippableTemplate(item['Group 2'])}</td>
    <td>${item['Description']}</td>             
    <td>${item['Description2']}</td>
</tr>`;

I want to insert conditional statements in it like

if (item['A'] != item['B'])
  $('<td></td>').text("Great!").appendTo(tr);
else
  $('<td></td>').text("Oops").appendTo(tr);

How do I go about doing that?

Any kind of help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 1870

Answers (2)

Shiladitya
Shiladitya

Reputation: 12181

Here you go with a solution https://jsfiddle.net/vh1bmfuz/

var item = { Category: 1, Description: 'Description 1.1', 'Description 2': 'Description 1.2', status: 'Status 1', 'Group 1': 'group1.1', 'Group 2': 'group1.2', 'A': 1, 'B': 2}

var matchMethod = function(){
  return ((item['A'] != item['B']) ? 'Great' : 'Ops');
}


var tr = `<tr>
    <td>${item['Group 1']}</td>
    <td>${item['Group 2']}</td>
    <td>${item['Description']}</td>             
    <td>${item['Description 2']}</td>
    <td>${matchMethod()}</td>
</tr>`;

$('table').append(tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>

I've a method that will check & return a string based on condition matched.

Hope this will help you.

Upvotes: 2

Andy
Andy

Reputation: 63550

Why not create a function that takes your inputs, tests them, and then outputs the template?

function appendCell(a, b) {
  const word = a !== b ? 'Great' : 'Oops';
  return `<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>${word}</td></tr>`;
}

const a = 1;
const b = 2;
const output = appendCell(a, b);

OUTPUT

<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Great</td></tr>

Adjust the code for your requirements.

DEMO

Upvotes: 0

Related Questions