Select options Collection - Change the options in a drop-down list depending on the selected option in another drop-down list: - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Select

Description

Select options Collection - Change the options in a drop-down list depending on the selected option in another drop-down list:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<select id="car" onchange="ChangeCarList()">
  <option value="">-- Car --</option>
  <option value="VO">Volvo</option>
  <option value="VW">Volkswagen</option>
  <option value="BMW">BMW</option>
</select>//from  ww w.j a v  a 2 s  .  c  o  m

<select id="carmodel"></select>

<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V)-1', 'VO-2', 'VO-3'];
carsAndModels['VW'] = ['VW-1', 'VW-2', 'VW-3', 'VW-4'];
carsAndModels['BMW'] = ['B1', 'B2', 'B3'];

function ChangeCarList() {
    var carList = document.getElementById("car");
    var modelList = document.getElementById("carmodel");
    var selCar = carList.options[carList.selectedIndex].value;
    while (modelList.options.length) {
        modelList.remove(0);
    }
    var cars = carsAndModels[selCar];
    if (cars) {
        var i;
        for (i = 0; i < cars.length; i++) {
            var car = new Option(cars[i], i);
            modelList.options.add(car);
        }
    }
}
</script>

</body>
</html>

Related Tutorials