PropertyMaps.com Blog

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.

  1. an option object.
  2. 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) );
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon] 5 comments

5 Responses to “Dynamically populating ’select’ elements with javascript”

  1. phpsourcecode 2008 July 6th 11:50 pm

    nice post really help me

  2. Bill Bartmann 2009 September 3rd 12:15 am

    I’m so glad I found this site…Keep up the good work

  3. karol 2009 September 26th 8:04 am

    remarks about DOM level were enlightening. Thanks

  4. Richard Dunne 2010 March 1st 4:20 pm

    Your last line of code on this page is partially blocked by the Recent Readers table.

  5. gaurav chauhan 2010 June 19th 3:36 pm

    Thanks for this wonderfull piece of info..
    i was struggling with the same thing to work in FF.
    after reading this it got resolved in seconds..
    thanks once again

Leave a reply

You must be logged in to post a comment.