Not Available}

' I tried many way" /> Not Available}

' I tried many way" /> Not Available}

' I tried many way"/>

javascript: How to use ternary expression render in html?

2.2k Views Asked by At

Here is a javascript ternary operator codes.

'<p>{balance>0?(Stock: {{balance}}):<span class="text-danger">Not Available</span>}</p>'

I tried many ways in order to rendered proper in HTML, however has no luck.

Output: {balance>0?(Stock: {{balance}}):<span class="text-danger">Not Available</span>} Output expected: (Stock: 23) or Not Available (in red color)

Thank you in advance!

Below is part of codes that use for working with Bloodhound plugin.

var prodName_typehead = {
                    name: 'prod_name',
                    displayKey: 'name',
                    hint: (App.isRTL() ? false : true),
                    source: item.ttAdapter(),
                    limit: 20,
                    templates: {
                       suggestion: Handlebars.compile([
                            '<div class="media">',
                                  '<div class="pull-left">',
                                      '<div class="media-object">',
                                          '<img src="{{thumb}}" width="50" height="50"/>',
                                      '</div>',
                                  '</div>',
                                  '<div class="media-body">',
                                      '<p><strong>{{name}}</strong></p>',
                                      '<p>{{desc}}</p>',
                                       '<p>{balance>0?(Stock: {{balance}}):<span class="text-danger">Not Available</span>}</p>',
                                  '</div>',
                            '</div>',
                          ].join(''))
                    }
                  };
1

There are 1 best solutions below

5
ngood97 On

I believe what you want is this:

`<p>${balance>0?`Stock: ${balance}`:`<span class="text-danger">Not Available</span>`}</p>`

When I run this:

balance = 0
`<p>${balance>0?`Stock: ${balance}`:`<span class="text-danger">Not Available</span>`}</p>`

I get:

"<p><span class="text-danger">Not Available</span></p>"

And when I run this:

balance = 1
`<p>${balance>0?`Stock: ${balance}`:`<span class="text-danger">Not Available</span>`}</p>`

I get:

"<p>Stock: 1</p>"

I'm using javascript template literals to complete the variable substitution you were going for.

(Basically the issue you were having is that you needed ticks (`) instead of double quotes (") to make a template literal as NarayaN alluded to in his comment, a $ before the first bracket to start the javascript embed and then nesting this same logic for the balance inside the first string option.)