skip to Main Content

How can I insert the if condition inside of ${ } using jQuery.

$('#inactive_list_body').append(`
<tr>
    <td>${value['name']}</td> 
    <td>${ if(value['status'] == 'false'){           
       value['identifier']}else{value['status']} }</td> 
    // ^^^^ Here I need to add IF condition
    <td>${value['reason_without_or_inactive']}</td>
</tr>
`);

3

Answers


  1. You could set that variable outside of your append method.

    let status = value['status'] ? value['status'] : value['identifier']

    Then you can use it as <td>{status}</td>

    Login or Signup to reply.
  2. You can use the ternary operator ?:

     <td>${value['status'] == 'false' ? value['identifier'] : value['status']}</td>
    
    Login or Signup to reply.
  3. var === 'something' ? 'something' : 'not something' construction may be used directly inside ${ } block:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <body>
       <p></p>
       <script>
           var a = 'a';
           $('p').append(
             `<tr><td>${a === 'a' ? 'a is a' : 'a is not a'}</td></tr>`
           );
       </script>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search