-2

How can I make ternary operator work if I have the following codes?

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

Thank you!


Sorry about that, maybe my question is not clear. Let me elaborate more here I'm using Bloodhound library to provide a suggestion drop down list. And the code as shown as below.

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 ? `<span class="danger">Not available</span>`:`(Stock: ${balance})`}</p>`,
                        '</div>',
                  '</div>',
                ].join(''))
              }
            };
user610983
  • 855
  • 2
  • 9
  • 14
  • This is not valid JavaScript. Could you elaborate? – Alberto Chiesa Aug 28 '20 at 09:09
  • 2
    user ` instead of ' and add a $ before each { – Alexandre Nicolas Aug 28 '20 at 09:09
  • @A.Chiesa: that looks like valid JavaScript, although it's a string and not a template-literal. – David Thomas Aug 28 '20 at 09:11
  • @A.Chiesa Why is this _"not valid JavaScript"_? o.O That's just a plain old string literal – Andreas Aug 28 '20 at 09:11
  • @DavidsaysreinstateMonica, Andreas. Yes you are both right. I meant something different: what is inside the string is not JavaScript code, is just a string. And, if you consider what's inside the string as code, it's not valid. I short circuited all of this and came out with something not true. Sorry for the confusion. – Alberto Chiesa Aug 28 '20 at 09:16

1 Answers1

0

Try like below.

`<p>${balance==0 ? `<span class="danger">Not available</span>`:`(Stock: ${balance})`}</p>`

Check below results for balance = 0 & balance = 1.

let balance = 0;
let result = `<p>${balance==0 ? `<span class="danger">Not available</span>`:`(Stock: ${balance})`}</p>`;
console.log('balance = 0 ->', result);

balance = 1;
result = `<p>${balance==0 ? `<span class="danger">Not available</span>`:`(Stock: ${balance})`}</p>`;
console.log('balance = 1 ->', result);
Karan
  • 12,059
  • 3
  • 24
  • 40