JavaScript: IIF like statement

111,042

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);
Share:
111,042
Alex Guerin
Author by

Alex Guerin

Updated on July 16, 2022

Comments

  • Alex Guerin
    Alex Guerin almost 2 years

    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 = '<option value="' + col + '">Very roomy</option>');
    

    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.

  • gilly3
    gilly3 over 12 years
    @RobG - Including the selected attribute in an <option> in HTML is equivalent to setting the selected property of an option element to true.
  • Youstay Igo
    Youstay Igo over 8 years
    Are you sure there are 3 = (===) signs? In some web resources I read you ought to put 2 = (==) only. Please clarify the matter. smipple.net/snippet/dsheardown/Javascript%20IIF%20example
  • Abhishek
    Abhishek over 8 years
    @YoustayIgo in javascript === means "strict equality" whereas == means "equality with coercion". While in this case you would be hard pressed to find a value for col where it matters, in general you want to prefer the === version unless you specifically want coercion. For more thoughts on this see Javascript the Good Parts which is basically the bible for many javascript developers. (In that there's many disagreements and factions but most agree its generally the right idea)
  • Youstay Igo
    Youstay Igo over 8 years
    Thx for the clarification :)