I need a little javascript help (easy)

function addOption(selectbox, val, txt){ ...... } addOption(list, "Cars", "Cars"); 

I need to add this before the function text:

      

So, there is a space before the option text ... It doesn’t matter what it is for, it’s just confusing ... I just don’t know how to insert it into js code.

If I do it like this:

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

Then     included in the text, so it is displayed to users. However, I need this to be interpreted as "space" ...

If you do not 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); } 
+4
source share
4 answers

Show addOption function addOption . There should be something wrong here, as the following HTML does what you want:

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

Update:. You set option s .text instead of your innerHTML - this is why spaces become escaped. Try the following:

 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 can use string literals ( \xNN ) to force the string character: \x20 . This will not help in your case.

+2
source

A simple solution? Use

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

instead of &nbsp; . Repeat n times after:

 // 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); 
+2
source

Are you linking to a list box (select / option)? You do not need &nbsp; , simple spaces will be executed. ' '

+1
source

Use innerHTML instead of text to prevent encoding ...

 optn.innerHTML = '&nbsp;&nbsp;&nbsp;Test'; 
0
source

Source: https://habr.com/ru/post/1310029/


All Articles