Skip to content Skip to sidebar Skip to footer

Ternary Operation Js Not Working

I try do this: $('#hire_button').html(data.code == 500 ? ''); But

Solution 1:

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.

Solution 2:

+ 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

Solution 3:

try this:

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

Post a Comment for "Ternary Operation Js Not Working"