Dynamically populating ’select’ elements with javascript
new Option(text,value);
As referenced in many javascript sources including “The Book” is bad, and should not be used. new Option forces browsers to use an older DOM model (0 or 1) instead of the now modern level 2.
The DOM does not mix and match so doing:
selectBox.appendChild(new Option(text,value));
fails in IE.
The fix is to use the DOM1 level support which is the ‘add’ method on the select element.
selectBox.add(new Option(text,value));
Problem with this is the way the spec was written for the ‘add’ method. It takes 2 parameters.
- an option object.
- the index position you want to insert it into your select element.
The spec defines that the second parameter should be null instead of undefined in order to append to the end of the list. This means that in any browser that follow the spec the second parameter must be explicitly set. This is one rare example where I prefer IE’s implementation.
// in FF or W3C compliant browser selectBox.add(new Option(text,value),null);
Problem with this is IE does not understand the null and fails. so you have to wrap this in a try catch.
try {
selectBox.add(new Option(text,value),null);
} catch(ex){
selectBox.add(new Option(text,value));
}
The solution is to use all DOM2 commands and stay far away from ‘new Option’.
var option = document.createElement('option');
option.setAttribute('value','value');
option.appendChild(document.createTextNode('text'));
selectBox.appendChild(option);
it is also important to note that using the DOM2 creation of the ‘option’ element does not work with the ‘add’ method on the ’select’ method in any browsers.
Totally compatible mootools shorthand, and my current accepted solution:
selectBox.appendChild( new Element('option', {'value' : value }).appendText(text) );
No comments yet. Be the first.
Leave a reply


