views:

189

answers:

3

I just found out that in FF, if you are dynamically creating an OPTION DOM element inside a SELECT element and just set its innerHTML, it sets both the innerHTML i.e. the displayed text as well as the value of the OPTION.

var opt = document.createElement('OPTION'); opt.innerHTML = 'Opt';

this set the "value" attribute as well of the element.

Is this correct behavior? I haven't been able to replicate this for IE.

A: 

What's happening, as far as I understand, is that if you check for the attribute value of an option

alert(opt.value);

It will return the value attribute value if it exists, but will return the value contained within the option tags as a fallback. In your example, you can independently set the value attribute with

opt.value = "some value"

If you do that, the value and innerHTML values will return independent values.

Zurahn
+1  A: 

If you don't specifically set a different value for the value attribute, it defaults to the text in the option.

Whether it's the correct behavior or not for the innerHTML attribute to change the value attribute is not possible to say. The innerHTML attribute is not covered by the standards, so if there is anything that is correct behaviour it would be not to support the attribute at all.

You shold rather use the text attribute to set the text of the option, which is the attribute specified in the standards.

Guffa
A: 

innerHTML is not well defined here.

https://developer.mozilla.org/En/DOM/Element.innerHTML

As there is no public specification for this property, implementations differ widely. For example, when text is entered into a text input, IE will change the value attribute of the input's innerHTML property but Gecko browsers do not.

you may use something like the following code for adding option elements to a select element:

var elOptNew = document.createElement('option');
elOptNew.text = 'Insert' + num;
elOptNew.value = 'insert' + num;
var elOptOld = elSel.options[elSel.selectedIndex];  
try {
  elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
}
catch(ex) {
  elSel.add(elOptNew, elSel.selectedIndex); // IE only
}
henchman