简体   繁体   中英

Adding dynamic content to a select option list using js

I have two drop down select input types on a html page.

Content's of 1st select drop down is as shown. The 2nd select is empty initially.

<select id="box1" name="box1">
    <option selected="selected" value="">--Select-One--</option>
    <option value="Apple"> Apple </option>
    <option value="Orange"> Orange </option>
</select>

I have added a js function which is called onchange of the 1st select box and updates the 2nd select (ie box2)

var select1 = document.getElementById("box1");
select1.onchange = function() {
    var select2 = document.getElementById("box");
    while (select2.firstChild) {
        select2.removeChild(select2.firstChild);
    }
    for ( var i = 1; i < select1.options.length; i++) {
        if (select1.selectedIndex == i)
            continue;
        var o = document.createElement("option");
        o.value = select1.options[i].value;
        // o.selected = "selected";
        o.text = select1.options[i].text;
        select2.appendChild(o);
        alert("Here " + i);
    }
}

This is working quite well in chrome and firefox, but not in IE. I guess probably it's the appendChild causing the problem in IE.

Please any hints to fix this probably for different versions of IE?

Note:

  1. Tested on IE 9.
  2. Have checked other questions on same error, but most of them were wrt to the table rows.

如果必须使用跨浏览器功能,我建议您使用jQuery之类的Javascript库,在jQuery中您可以执行以下操作:

jQuery("#selectId").append('<option value="' + text + '">' + text + '</option>');

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