views:

115

answers:

4
  function addOption(selectbox, val, txt){
  ......
  }

  addOption(list, "Cars", "Cars");

I need to add this in front of the text of the function:

     

So that there is space coming in before the option text...Never mind what it is for, it is just confusing... I just don't know how to insert it into the js code.

If I do it like this:

  addOption(list, "Cars", "   Cars");

Then the     comes into the text, so it gets displayed for the users. However I need it to be interpreted as "space"...

If you don't understand let me know...

How can I do this? Quotes, double quotes etc?

Thanks

UPDATE:

function addOption(selectbox, value, text, cl )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    if (cl==1){ optn.className = "nav_option_main"; }
    selectbox.options.add(optn);
}
+3  A: 

Show the code of the addOption function. Something must be going wrong there, since the following HTML does what you want:

<select>
 <option>foo</option>
 <option>&nbsp;bar</option>
</select>

Update: You’re setting the option’s .text instead of its innerHTML — that’s why the spaces get escaped. Try this:

function addOption(selectbox, value, html, cl) {
 var optn = document.createElement('option');
 optn.innerHTML = html;
 optn.value = value;
 if (cl) {
  optn.className = 'nav_option_main';
 };
 selectbox.options.add(optn);
};

In JavaScript, you could use string literal escapes (\xNN) to force the string character: \x20. That won’t help in your case though.

Mathias Bynens
check my edit for the function
Camran
@Camran: I've updated my answer.
Mathias Bynens
@Camran: See my warning about assigning to `innerHTML`. It is *really* not what you should do.
Tomalak
+2  A: 

Easy solution? Use

String.fromCharCode(160)  // char code 160 is nbsp

in place of &nbsp;. Repeat n times via:

// n = 3 in this case
Array(3).join(String.fromCharCode(160)); 

So...

function addOption(selectbox, val, text, indent){
  if (typeof indent == "number" && indent > 0)
    var indentStr = Array(indent).join(String.fromCharCode(160));
  else
    var indentStr = "";

  var optn = document.createElement("OPTION");
  optn.text = indentStr + txt;
  optn.value = value;
  selectbox.options.add(optn);      
}

addOption(list, "Cars", "Cars", 3);
Tomalak
+1  A: 

Are you refering to list box (select/option)? You don't need &nbsp;, simple white spaces ' ' will do.

MasterGaurav
A: 

Use innerHTML instead of text to prevent encoding...

optn.innerHTML = '&nbsp;&nbsp;&nbsp;Test';
Josh Stodola
Wont this be "dangerous" like in my Q comment by Tomalek?
Camran
@Camran No, I don't think you have anything to be worried about there. Not sure what "danger" he's talking about
Josh Stodola