JSFiddle - React, Tailwind, and code Playground

by Sidon Duarte

HTML

<!-- By Sidon Duarte - 2017 -->
<body>
    <h1>Populate select list using javascript
</h1>
    <p>Select the Brand and then the next box (Car) will be populated:</p>

    <div class="select-style">
    <br />Brand:
    <select required id="brand">
    </select>

    <br />  
    <br />Car:     
    <select id="car" >
        <option value=""> </option>
    </select>
  </div>
      
</body>

CSS

body {
  margin-left: 30px
}

.select-style {
    width: 220px;
    height: 100%;
    border-radius: 3px;
}

.select-style select {
    padding: 5px 8px;
    width: 100%;
}

JavaScript

// By Sidon - 2017
$(document).ready(function(){

    $('#brand').change(function() {populateCar()});  
  
    var ford = ['Fiesta', 'Focus', 'Fusion', 'Taurus', 'Mustang'];
    var vw = ['Passat', 'Tiguan', 'Golf', 'Jetta', 'Up']
    var fiat = ['Punto', '500', '500 City', 'Panda', 'DoblĂ´']
    var cars =  {'Ford': ford, 'Volks': vw, 'Fiat': fiat}
    var brands = ['Ford','Fiat', 'Volks']
    populateBrand()
  
  
    function populateBrand() {
        $("#brand").empty();
        $("#brand").append('<option value="" disabled selected>Select your option</option>');
        $.each(brands, function(v) {
            $('#brand')
                .append($("<option></option>")
                .attr("value", brands[v])
                .text(brands[v]));
        })
    }


    function populateCar(event) {
        brand = $("#brand option:selected" ).text();
        $("#car").empty();
        for (let [k, v] of Object.entries(cars)) {
            if(k==brand) {
                for (car in cars[brand]) {
                    var opt = document.createElement("option");
                    opt.value = cars[brand][car];
                    opt.innerHTML = cars[brand][car];
                    document.querySelector('select[id="car"]').appendChild(opt);
                }
            };
        }
    }
 
});