I'd like to add an <option> element to a <select> element where the <option> element's text contains an HTML entity: —
In HTML, the code would look like this:
<select name="test" id="test">
<option value="">— Select One —</option>
</select>
My JavaScript code looks like this:
function selectOne() {
var e = document.getElementById('test');
e.options[0] = new Option('— Select One —', '');
}
However, as you will see if you test this, the — becomes escaped. I had the same outcome when I tried:
e.options[o].text = '— Select One —';
(Observed behavior was in Internet Explorer 7 ... did not test with Firefox, Safari, etc. -- Internet Explorer 7 is the only browser I need at the moment.)
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 = '— Select One —';
I just realized I could use a Unicode JavaScript escape:
e.options[0] = new Option('\u2014 Select One \u2014', '');
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 —', '');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With