nowiko
nowiko

Reputation: 2557

Ternary operation JS not working

I try do this:

$('#hire_button').html(data.code == 500 ?  "<span class='alert alert-danger>" : "<span class='alert alert-success>" + data.info + "</span>");

But it returns or success> or empty row. What I am doing wrong?

Upvotes: 0

Views: 121

Answers (3)

Alnitak
Alnitak

Reputation: 339816

The ? : ternary operator has lower precedence that the + concatenation operator so you're building mis-matched tags.

However, IMHO you should refactor your code to avoid some repetition, and automatically fixing the precedence issue at the same time:

$('#hire_button').empty().append($('<span>', text: data.info, class: 'alert'})
   .addClass(data.code == 500 ? 'alert-danger' : 'alert-success'));

NB: above rewritten as the original incorrectly added the new class to the button instead of the enclosed span.

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

+ has a greater operator precedence over ternary operators. Group 'em to be clear.

$('#hire_button').html((data.code == 500 ? 
  "<span class='alert alert-danger>" : 
  "<span class='alert alert-success>") + data.info + "</span>");

Grouping operator is what you're using here as it has the highest precedence.

MDN ON OPERATOR PRECEDENCE

Upvotes: 2

Alex Barannikov
Alex Barannikov

Reputation: 304

try this:

$('#hire_button').html(data.code == 500 ?  "<span class='alert alert-danger>" : ("<span class='alert alert-success>" + data.info + "</span>"));

Upvotes: -1

Related Questions