Dynamically populating a select

Note that the versions step through the whole thing.

by jazahn

HTML

<select id="first">
    <option>---</option>
    <option value="one">one</option>
    <option value="two">two</option>
</select>
<select id="second">
    <option>---</option>
</select>

JavaScript

var first = $("#first");
var second = $("#second");

var obj = {
    "one": ["1", "2", "3", "4"],
    "two": ["10", "20", "30", "40"]
}

var removeAllOptions = function(){
    // set them all to 0
    second[0].options.length = 0;
}

first.on("change", function(){
    removeAllOptions();
    if(first.val() !== "---"){
        obj[first.val()].forEach(function(item){
            var option = document.createElement("option");
            option.value = item;
            option.className = "secondOpt";
            option.appendChild(document.createTextNode(item));
            second[0].appendChild(option);

        });
    } else {
        var option = $(document.createElement("option"));
        option.val('---');
        option[0].appendChild(document.createTextNode("---"));
        second[0].appendChild(option[0]);
    }
    
});