1

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>");
4
  • JavaScript doesn't allow line breaks inside string constants (yet). Commented Oct 27, 2012 at 12:50
  • @Pointy: Unless you escape it with a backslash, at least. Commented Oct 27, 2012 at 12:54
  • 1
    You are looking for the ternary operator? Commented Oct 27, 2012 at 12:55
  • @Bergi right; and even then it's not supported by all interpreters I don't think. I personally don't think that's a good idea as the handling of start-of-line whitespace is problematic. Commented Oct 27, 2012 at 12:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I did try this $(this).html("<select id=\'status\' name=\'status[]\' multiple><option value=\'1\'" +(selected.indexOf(1) ? "\' SELECTED\'" : "") +"></option></select>"); It doesnt work at all. However $(this).html("<h1>TEST</h1>"); works just fine.
@NikolajSvendsen well when you say "doesn't work at all" - is a JavaScript error reported? Is the result incorrect?
It says that selected.indexOf is not a function
@NikolajSvendsen What is the value of "selected"? For "indexOf" to work, it has to be an array or a string.
var selected = $(this).data("selected"); Which contains "1,5,7,2"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.