views:

591

answers:

1

Hi, How can I realize this solution? dropdownlist values depend on another dropdownlist in the same form e.g. :a form contains dropdownlist(car_name),dropdownlist (models of this car),button(search) notice that : 1)car_model values depend on car_name value 2)car_name dropdownlist and car_model dropdownlist in the same form

thanks Best Regards.

A: 
<form>
<select id="car_name">
    <option value="car1">Car 1</option>
    <option value="car2">Car 2</option>
    <option value="car3">Car 3</option>
</select>
<select id="car_model">
</select>
</form>
<script type="text/javascript">
// Maps all available car models
var modelMap = {
    'car1': [
        // Each entry contains the model's ID and text/label.
        ['car1-1', 'Car 1.1'],
        ['car1-2', 'Car 1.2'],
        ['car1-3', 'Car 1.3']
    ],
    'car2': [
        ['car2-1', 'Car 2.1'],
        ['car2-3', 'Car 2.2']
    ],
    'car3': [
        ['car3-1', 'Car 3.1'],
        ['car3-2', 'Car 3.2'],
        ['car3-3', 'Car 3.3'],
        ['car3-4', 'Car 3.4'],
        ['car3-5', 'Car 3.5']
    ]
};

// Get the dropdown list elements.
var nameList = document.getElementById('car_name');
var modelList = document.getElementById('car_model');

// Function to be called when the car name is changed
nameList.onchange = function() {
    // Get the selected car.
    var selectedName = nameList.options[nameList.options.selectedIndex].value;
    // Lookup available models in the map.
    var availModels = modelMap[selectedName] || [];

    var i, opt;

    // Set available models in the model dropdown.
    for (i = 0; i < availModels.length; ++i) {
        opt = availModels[i];
        modelList.options[i] = new Option(opt[0], opt[1]);
    }

    // Remove all old options if the new car has fewer models than a previous selection.
    for (; i < modelList.options.length; ++i) {
        modelList.options[i] = null;
    }
};
</script>
Ferdinand Beyer