Dependent Selects with Pure JS

Selects dependientes a partir de un JSON object, realizado con solo JAvaScript sin frameworks

by Porfirio Chavez

HTML

<form>
    <p>
        <select id='select1' onchange='cargarSelect2(this.value);'>
            <option value='0'>Selecciona una opción</option>
        </select>
    </p>
    <p>
        <select id='select2' onchange='cargarSelect3(this.value);'>
            <option value='0'>Selecciona una opción</option>
        </select>
    </p>
    <p>
        <select id='select3'>
            <option value='0'>Selecciona una opción</option>
        </select>
    </p>
</form>

JavaScript

var vehiculos = {
        "autos":[
            {"marca":"Ford", "modelos" : ["Focus", "Fiesta", "Mondeo"]},
            {"marca":"Seat", "modelos" : ["León", "Ibiza"]},
            {"marca":"Opel", "modelos" : ["Corsa", "Zafira", "Astra"]}
        ],
        "motos":[
            {"marca" : "Honda", "modelos" : ["CBR450", "VFR800F"]},
            {"marca" : "Yamaha", "modelos" : ["SR400"]}
        ]
    }

    function restablecerSelectBox(id){
        var selectBox = document.getElementById(id);
        while (selectBox.firstChild) {
            selectBox.removeChild(selectBox.firstChild);
        }
        selectBox.options[0] = new Option("Selecciona una opción", "0");
    }

    function cargarSelect1(){
        var selectBox = document.getElementById("select1");
        var typeVehicle = Object.keys(vehiculos).length;
        for (var i = 0; i < typeVehicle; i += 1) {
            var option = document.createElement("option");
            option.value = Object.keys(vehiculos)[i];
            option.text = Object.keys(vehiculos)[i];
            selectBox.appendChild(option);
        }
    }

    function cargarSelect2(valorTipo) {
        restablecerSelectBox("select2");
        restablecerSelectBox("select3");

        var currentSelectBox = document.getElementById("select2");

        var brands = vehiculos[valorTipo];
        if(brands.length > 0){
            for(var i = 0; i < brands.length; i += 1){
                var option = document.createElement("option");
                option.value = brands[i].marca;
                option.text = brands[i].marca;
                currentSelectBox.appendChild(option)
            }
        }
    }

    function cargarSelect3(valorMarca){
        restablecerSelectBox("select3");

        var currentSelecBox = document.getElementById("select3");

        var brands = vehiculos[document.getElementById("select1").value];
        if(brands.length > 0){
            for(var i = 0; i < brands.length; i += 1){
             ...