JavaScript: IIF like statement

JavaScript: IIF like statement

Coming from VB, JavaScript isn’t very easy to get the hang of. Please don’t be negative, I’ve tried and searched loads but with no luck. BTW, I’m creating a dropdown control initialized from a Select option list in JS.
Dummy code:
var col = ‘tardis’;
var x = ‘‘);

I would like to add selected after the value of col ONLY if col is equal to ‘screwdriver’.
I’ve tried using the IF statement with the ? and the : but can’t seem to get my head around it. Having ” as the false value does not work. No items are selected and the list is blank. Remove the IF statement and all works.
Any ideas and again, sorry for the newb-ness.

Solutions/Answers:

Solution 1:

'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';

Solution 2:

var x = '<option value="' + col + '"'
if (col == 'screwdriver') x += ' selected';
x += '>Very roomy</option>';

Solution 3:

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

Solution 4:

If your end goal is to add elements to your page, just manipulate the DOM directly. Don’t use string concatenation to try to create HTML – what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:

var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";

Then, later when you put the element in your page, instead of setting the innerHTML of the parent element, call appendChild():

mySelectElement.appendChild(x);

Solution 5:

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

References

Related:  Is it really insecure to build HTML strings in Javascript?