Search code examples
javascripthtmlinternet-explorerappendchild

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 (i.e. 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 w.r.t to the table rows.

Solution

  • If cross browser functionality is a must i recommend you to use a Javascript library like jQuery, in jQuery you can do something like this:

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