views:

2604

answers:

3

I'd like to add an <option> element to a <select> element where the <option> element's text contains an HTML entity: &mdash;

In HTML, the code would look like this:

<select name="test" id="test">
<option value="">&mdash; Select One &mdash;</option>
</select>

My Javascript code looks like this:

function selectOne() {
  var e = document.getElementById('test');
  e.options[0] = new Option('&mdash; Select One &mdash;', '');
}

However, as you will see if you test this, the &mdash; becomes escaped. I had the same outcome when I tried:

e.options[o].text = '&mdash; Select One &mdash;';

(observed behavior was in IE7 ... did not test with FireFox/Safari/etc -- Ie7 is the only browser I need at the moment).

+5  A: 

You don't need to escape the entity - it works like this:

function selectOne() {
      var e = document.getElementById('test');
      e.options[0] = new Option('— Select One —', '');
}
Andrew Hare
True -- but I was thinking about ANY HTML entity... like a «
Adam Douglass
This does work for any HTML entity, though it can run into encoding problems. Your unicode escape sequences are probably the most portable solution.
Ben Blank
+4  A: 

I just realized I could use a unicode javascript escape:

e.options[0] = new Option('\u2014 Select One \u2014', '');
Adam Douglass
Great conversion utility: http://rishida.net/scripts/uniview/conversion.php
Adam Douglass
Both this solution and Chetan's solution work. It just depends on which style you prefer. For me, I prefer to set the value once instead of going back and changing it afterwards like in Chetan's solution.
brian buck
+1  A: 

text property doesn't get unescaped, as it is meant to be taken literally. If you use innerHTML, the entities get converted to corresponding characters.

e.options[o].innerHTML = '&mdash; Select One &mdash;';
Chetan Sastry