[Javascript] The Non-Breaking Space of Doom

Andrew Crawford javascript at evermore.com
Mon Jan 9 22:16:28 CST 2006


Greetings All,

It seems like this would be a fairly common problem with a simple
solution but, after experimenting and doing dozens of Google searches, I
appear to be the only one who has ever run into this.  So, I figure I
must be doing something horribly wrong or non-standard.  I hope someone
here can shed some light on this for me.

I am trying to have JavaScript in a page retrieve some data based on the
item chosen in a form select list and return a different (dependent)
select list (ala the AJAX approach).  Shockingly enough, that all works
pretty much as it should.

Where I am running into problems is in the formatting when creating the
new select list.  The new select list being generated contains a
hierarchical list.  Something like this:

Item-1
  Item-1.1
  Item-1.2
    Item-1.2.1
Item-2
  Item-2.1

[Example 1]

To make this look nice as a select list, the spaces become non-breaking
space characters ( ) in the HTML.  So, the code that goes to the
browser is:

Item-1
 Item-1.1
 Item-1.2
  Item-1.2.1
Item-2
 Item-2.1

[Example 2]

However, the list displays as in the first example (Example 1) when the
select list is all hard coded in HTML.  So far, so good.

The problem appears when trying to generate the same select list with
JavaScript.  My loop that builds the option elements looks like this:

for(r in rows) {
    var newelementidx =
window.top.document.getElementById('form_folder').options.length;
    document.getElementById("form_folder").options[newelementidx] = new
Option(rows[r].label, rows[r].id, false, false);
}

The label contains the text description (label) for the current option
element.  For instance, on the second pass in the examples above label
would be " Item-1.1"  So, it should produce output just like
Example 2 above and, presumably, display just like Example 1.  It does not.

When JavaScript generates the select list, it displays like the second
example above (Example 2) instead of the first (Example 1).  That is, it
actually displays " " instead of putting a non-breaking space
character.  Using a bookmarklet to examine the generated source, it
shows that JavaScript is returning " " instead of just " "

I have tried using a regex string replace to fix it in various ways,
including using a slash to escape the & character, using \x26 in place
of the & character, etc.  Nothing seems to work.

So, does anyone know what is going on and how to get around it or,
alternately, how I should be generating my select list to avoid this
problem?

Andrew Crawford



More information about the Javascript mailing list