简体   繁体   中英

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.

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)

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

以我的经验,用纯JavaScript appendChild()方法替换jQuery的append()导致我的项目出现在选择框中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM