9

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)?

10 Answers 10

12

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 :(

4
  • 3
    But I NEED that IE 4 solution.
    – keparo
    Nov 15, 2008 at 6:50
  • Err... are you beyond certain you need IE4? Because that's a pretty ancient version -- it's for Windows 95. Nov 15, 2008 at 7:13
  • 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
    Nov 15, 2008 at 11:27
  • 1
    Fails in IE4 because of getElementById. Try "document.forms[0].<select-name>" Nov 15, 2008 at 15:59
6

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

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

You shouldn't be using the Select.add method, as it's broken in IE, and there are better ways to add options dynamically (see http://msdn.microsoft.com/en-us/library/ms535921(VS.85).aspx)

I have had the same problem, and have found that the best way is to use the Node.insertBefore method. This has the advantage of working in all browsers, and making sorting of the elements easy, because you don't have to add the element as the last element of the select list in IE. For example, adding an option from one select list to another, so that the options in the target list are sorted alphabetically, can be done like this:

/*
adds an option to select element, alphabetically sorted according to the lower case value of the display element (option.text)
*/

function insertOptionToList(optionToInsert, targetSelectElement){

    for (var i=0;i<targetSelectElement.options.length;i++){
        var tempOptionText = targetSelectElement.options[i].text;
        if(tempOptionText.length>0 && optionToInsert.text.toLowerCase()<tempOptionText.toLowerCase()){
            targetSelectElement.insertBefore(optionToInsert,targetSelectElement[i]);
            return true;
        }
    }
    targetSelectElement.options[targetSelectElement.options.length] = optionToInsert;
    return true;                        
}
2

I would suggest using DOM-methods instead.

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

Never had issues with that.

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

using the addOption function from the jQuery selectboxes plugin

1
  • or with jquery without the plugin $('#' + selectId).append($('<option></option>').attr('value', value).text(display));
    – enobrev
    Nov 15, 2008 at 6:01
1

This worked for me

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

1

I did some research myself using all permutations and combinations of creating an option object and I hope this is the best possible way by which we can add options to select in a browser neutral way:

function populateSelectField()
{

    document.frmMain.fldSelect.options.length = 0;
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 1");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 2");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 3");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 4");
}

Since the select field object is accessed and manipulated by accessing it's parent object, which is "frmMain" (form) in this code, it doesn't create any problem for any browser to run the code.

This is supported by all browsers including IE.

0

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]);
    }
0

(edit: this doesn't work in IE, so it's not recommended.)

I do it by changing the innerHTML:

<select id="selectItem"></select>

var s=document.getElementById("selectItem");
s.innerHTML+="<option>apples</option>";
s.innerHTML+="<option>bananas</option>"; //(...etc)

Or put it in a loop if you are using an array to populate your dropdown list.

1
  • Can you expand this answer to cover IE as well? Oct 4, 2012 at 18:17
-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.