Search code examples
javascripttemplate-literalstemplate-strings

If Else Condition Not Working In Javascript Template Literals


I am getting issue while displaying my table data inside tbody, in my javascript i am getting result object and i am using template literals inside javascript file Here's my code:

for (i = 0; i < size; i++) 
{
    serialNo++;
    html += `<tr>
    <td>${serialNo}</td>
    <td>${result[i].first_name}</td>
    <td>${result[i].last_name}</td>
    <td>${result[i].email}</td>
    <td>${result[i].mobile}</td>
    (${(result[i].status == 1)} ? '<td><div class="switchery-demo">
    <input type="checkbox" checked id="demo${result[i].contact_id}" 
    onclick="status_item(this,'${result[i].contact_id}')" 
    data-plugin="switchery" data-size="small" data-color="#1bb99a"/> 
    </div></td>' : '<td><div class="switchery-demo"><input 
    type="checkbox" checked data-plugin="switchery" 
    id="demo${result[i].contact_id}" 
    onclick="status_item(this,'${result[i].contact_id}')" data- 
    size="small" data-color="#1bb99a"/></div></td>')
    </tr>`;
}

In result[i].status i am using ternary operator i am checking if status == 1 then display first one else second but it is creating two instead of one i don't know where i am going wrong kindly help.


Solution

  • You need to move the whole part into the expression part

    `${ result[i].status == 1
        ? '...'
        : 'some other'
    }`
    

    Example with nested template strings.

    console.log(`${true === false
        ? `${ 10 }`
        : `${ 20 }`
    }`);