Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Options to select drop down in IE

I'm trying to add items to a select drop down at run time. So far it's working in Firefox and Opera, but it doesn't seem to work in IE7 or 8.

What is supposed to happen is that when a user selects a center, then the personnel drop down gets populated with the personnel at the center....

//Clear out the all of the exisiting items
if (document.getElementById("ddlPersonnel").hasChildNodes) {
    while (document.getElementById("ddlPersonnel").childNodes.length > 0) {
        document.getElementById("ddlPersonnel").removeChild(document.getElementById("ddlPersonnel").firstChild);
    }
}

//Add the "Select Personnel" option
var FirstOpt = document.createElement('OPTION');
FirstOpt.value = "";
FirstOpt.innerText = "Select Personnel";
alert("blah1");
document.getElementById("ddlPersonnel").options.add(FirstOpt, null);    //It dies here with a "Type Mismatch" error
alert("blah2");

It dies on the line between the two alerts with a "Type Mismatch" error.

like image 732
zort15 Avatar asked May 14 '09 13:05

zort15


People also ask

Which element do you use to add an item to a drop-down menu?

The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted).

How do I select all options in a drop-down list?

To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.

Which option below lets you select multiple HTML elements at the same time?

The <select> element has some unique attributes you can use to control it, such as multiple to specify whether multiple options can be selected, and size to specify how many options should be shown at once.


2 Answers

Use new Option instead of createElement.

var sel = document.getElementById("ddlPersonnel");
var opt = sel.options;
opt[opt.length] = new Option("Label","Value")

(That should work, but I haven't tested it)

like image 149
Quentin Avatar answered Oct 03 '22 05:10

Quentin


Just replace

document.getElementById("ddlPersonnel").options.add(FirstOpt, null);

by

document.getElementById("ddlPersonnel").add(FirstOpt);

Removing the ".options" and the ", null" in the add() function will do the trick

like image 41
hegyre Avatar answered Oct 03 '22 05:10

hegyre