views:

354

answers:

2

I have HTML output similar to this:

<select>
<option value="1">Item1 </option>
</select>

How do I use JavaScript to get the value "Item1 " (with the space) rather than "Item1"?

In Internet Explorer all the properties I've tried, e.g. text, innerHTML, data, nodeValue return "Item1" instead of "Item1 ".

Interestingly in Firefox, textContent and innerHTML return the untruncated value whereas text returns the truncated value.

+2  A: 

Sorry, IE's parser indeed throws away trailing spaces in <option>. Curiously, if you assign a string with trailing spaces to innerHTML IE manages to remember one of them. Probably best not relied on.

Normally if you want visible trailing spaces (in any browser) you have to use a non-breaking-space character (eg. &#160; character reference).

bobince
That's annoying. We had tried to avoid truncation/trimming of data in the system but this means we'll have to rethink that approach.
tjrobinson
Well the actual *data* should be in the 'value' attribute of course - the 'text' content is only for show.
bobince
Good point, though easier said than done in this particular case!
tjrobinson
A: 

You should never rely on spacing being interpreted literally. Maybe your output should be rendered as : <option value="1">Item1&nbsp;</option>

P.S.: It says HTML is ignored within a code block, yet my entity gets escaped here. (Markdown)

Cerebrus
To expand on this concept, the text of an option element was never meant to be used as data -- that's what the value attribute is for. It would seem that if you're using the text for any logic then you're possibly using the value attribute in an incorrect manner.
ken
I agree, very succinctly put.
Cerebrus