tags:

views:

1914

answers:

8

I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the standard, even as documented on the MSDN site.

My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?

  • Call the add method differently based on the value of the user agent?
  • Wrap the select object in a class that provides the proper method signature?
  • Use a javascript library which does this for you (specify which library)?
+8  A: 

Adding a new Option type works at least IE6 and up

function addOption(selectID, display, value)
{
  var obj = document.getElementById(selectID);
  obj.options[obj.options.length] = new Option(display, value);
}

Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully. IE4 failed :(

Zurahn
But I NEED that IE 4 solution.
keparo
Err... are you beyond certain you need IE4? Because that's a pretty ancient version -- it's for Windows 95.
Jeff Hubbard
IE4 failed because it doesn't support ‘document.getElementById()’ — you would have to use document.all. The ‘new Option()’ method itself works fine going back as far as Netscape 2.0!
bobince
Fails in IE4 because of getElementById. Try "document.forms[0].<select-name>"
Marko Dumic
+2  A: 

$("#selectID").addOption(value, text);

using the addOption function from the jQuery selectboxes plugin

Scott Evernden
or with jquery without the plugin $('#' + selectId).append($('<option></option>').attr('value', value).text(display));
enobrev
A: 

As I remember, IE4 accepts creation of an option element and appending it, but perhaps I don't recall it coorrectly !-)

roenving
+2  A: 

You can use a try-catch block for doing this :

              try
 {
  //Standards compliant
  list.add(optionTag, null);
 }
 catch (err)
 {
  //IE
  list.add(optionTag);
 }
Sanket
A: 

I would suggest using DOM-methods instead.

document.createElement('option') selectEl.appendChild()

Never had issues with that.

jishi
A: 

If you want to add an option to the start of the dropdown, the following variation should do it:

    try{
        list.add(optionTag, 0);
    } catch (err) {
        // Firefox is dumb for once: http://www.quirksmode.org/dom/w3c_html.html#selects
        list.add(optionTag, list.options[0]);
    }
EoghanM
A: 
simon
A: 

This worked for me

$(selectID).append($('<option>'+display+'</option>').attr('value', value));

Gabo