NikolajSvendsen
NikolajSvendsen

Reputation: 345

Jquery if statement inside .html

I have been trying to get some jQuery running replacing the html of an object. But how can i put an if statement inside, like this.

$(this).html("<select id=\'status\' name=\'status[]\' multiple><option value=\'1\'"+if(string_contains(selected, 1)) { document.write(\' SELECTED\'); }+"></option></select>");

The if statement makes it stop working.

And a little side question.

Why cant i break inside the .html like this:

        $(this).html("
<select id=\'status\' name=\'status[]\' multiple>
<option value=\'1\'"+if(string_contains(selected, 1)) { document.write(\' SELECTED\'); }+"></option>
</select>");

Upvotes: 1

Views: 722

Answers (1)

Pointy
Pointy

Reputation: 413682

What you've got is just syntactically incorrect.

$(this).html("<select id=\'status\' name=\'status[]\' multiple><option value=\'1\'" +
  (string_contains(selected, 1) ? "\' SELECTED\'" : "") +
  "></option></select>"
);

The if statement is just that — a statement. It doesn't work as part of a JavaScript expression. However, the ? : operator will do what you want. It takes the form:

query ? expr1 : expr2

The query expression is evaluated. If the result is "truthy", the overall result is the value of expr1; otherwise, it's the value of expr2. The operator precedence of ? : is pretty low so it's generally a good idea to parenthesize the whole thing.

Upvotes: 4

Related Questions