
Originally Posted by
scrapmetalca
I have the following code which replaces the contents of an option menu. It works fine on FireFox, but the new entries don't seem to appear on IE.
The option elements are added, but the text for them is not.
function changeText()
{
var x=document.getElementById("mySelect")
Using the forms and elements collections to reference form elements and form controls is supported across more browsers. However, if a function is called as a result of interaction with a form or form control, then even they shouldn't be necessary.
The posted code can be altered such that a reference to the form is passed to the changeText function:
HTML Code:
<input type="button" ... onclick="changeText(this.form);">
In this event listener, the this operator refers to the form control, and form controls have a form property that refers to the containing form (assuming one exists). From that reference, you can retrieve other form controls:
Code:
function changeText(form) {
/* e.g.: form.elements.mySelect */
If several controls will be referenced, the member expression can be shortened a little:
Code:
function changeText(form) {
var controls = form.elements;
/* controls.mySelect */
Historically, the length property of the select element itself was read-only. For backwards-compatibility, it's a better idea to manipulate the options through the options collection, only.
var option = document.createElement("option");
Further compatibility is also achieved using the "DOM 0" Option constructor function. However, if one is to employ feature detection, and a fallback is in place for unscriptable browsers, then that's less of a concern.
The problem you're facing is here. Adding text via the text property isn't supported properly in MSIE. Instead, one must create a text node (using the createTextNode method of the document object) and append that to the option element.
Mike
Bookmarks