Javascript: Append Children With Functions: FireFox vs Chrome

I have a test page based on a problem I've been experiencing:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <style type="text/css">
            #selectDiv { display: inline; }
        </style>
        <script type="text/javascript">
            function changeOption(args) {
                var sel = document.createElement("select");
                var opt1 = document.createElement("option");
                var opt2 = document.createElement("option");
                var opt3 = document.createElement("option");
                opt1.value = "opt1";
                opt1.appendChild(document.createTextNode("Option 1"));
                sel.appendChild(opt1);
                opt2.value = "opt2";
                opt2.appendChild(document.createTextNode("Option 2"));
                sel.appendChild(opt2);
                opt3.value = "opt3";
                opt3.appendChild(document.createTextNode("Option 3"));
                sel.appendChild(opt3);

                // working on FireFox, not on Chrome
                opt1.onclick = function() {changeOption()}
                opt2.onclick = function() {changeOption()}
                opt3.onclick = function() {changeOption()}

                document.getElementById("selectDiv").appendChild(sel);
            }
        </script>
    </head>
    <body>
        <h1>This is a test.</h1>
        <div id="selectDiv">
        <select id="test_select1" onchange="changeOption()">
            <option value="opt1">Option 1</option>
            <option value="opt2">Option 2</option>
            <option value="opt3">Option 3</option>
        </select>
        </div>
    </body>
</html>

In FireFox, this works as I would expect: each new select is created with three options; selecting one creates a new select with three options.

But in Chrome, it stops on the second select. That is, the newly created select doesn't seem to get the onclick function. The first select happily creates more selects, but that isn't what I'm looking for.

Safari behaves like Chrome but that's to be expected, right? I've tried a jQuery version, but it doesn't work either. Can anyone help me out here?

Answers


Bind a change handler to the select element, not a click handler on the options. So this:

sel.onchange = function(){
   changeOption();
}

Instead of:

opt1.onclick = function() {changeOption()}
opt2.onclick = function() {changeOption()}
opt3.onclick = function() {changeOption()}

Fiddle: https://jsfiddle.net/c1kmtnfd/


Need Your Help