Dynamic Drop down values based on another dropdown [closed]

You have given no HTML or any script you have tried yourself as such the below should serve as a good template for you to get started.

DEMO – Cascading dropdowns, show managers for selected department

Assuming the following HTML

<div>
    <div style="float: left;">
        Select Department
        <br />
        <select id="departments"></select>
    </div>
    <div style="float: left; margin-left: 10px;">
        Select Manager
        <br />
        <select id="managers"></select>
    </div>
</div>

‚Äč
When you have loaded the departments and managers from the database you can dynamically populate the selects with code similar to this:

var $departments = $("#departments");
var $managers = $("#managers");

// This data would be loaded from the DB
var departments = [
    {id: "1", value: "Department 1"},
    {id: "2", value: "Department 2"}
];

// This data would be loaded from the DB
var managers = [
    { departmentId: "1", value: "Dep 1 Manager 1"},
    { departmentId: "1", value: "Dep 1 Manager 2"},
    { departmentId: "1", value: "Dep 1 Manager 3"},
    { departmentId: "1", value: "Dep 1 Manager 4"},
    { departmentId: "1", value: "Dep 1 Manager 5"},
    { departmentId: "1", value: "Dep 1 Manager 6"},
    { departmentId: "1", value: "Dep 1 Manager 7"},
    { departmentId: "1", value: "Dep 1 Manager 8"},
    { departmentId: "1", value: "Dep 1 Manager 9"},
    { departmentId: "1", value: "Dep 1 Manager 10"},
    { departmentId: "2", value: "Dep 2 Manager 1"},
    { departmentId: "2", value: "Dep 2 Manager 2"},
    { departmentId: "2", value: "Dep 2 Manager 3"},
    { departmentId: "2", value: "Dep 2 Manager 4"},
    { departmentId: "2", value: "Dep 2 Manager 5"},
    { departmentId: "2", value: "Dep 2 Manager 6"},
    { departmentId: "2", value: "Dep 2 Manager 7"},
    { departmentId: "2", value: "Dep 2 Manager 8"},
    { departmentId: "2", value: "Dep 2 Manager 9"},
    { departmentId: "2", value: "Dep 2 Manager 10"}
];

function getManagers() {
    $managers.empty();

    var departmentId = $departments.val();

    for (i = 0; i < managers.length; i++) {
        if (managers[i].departmentId === departmentId) {
            $managers.append("<option value="" + managers[i].departmentId + "">" + managers[i].value + "</option>");
        }
    }
}

for (i = 0; i < departments.length; i++) {
    $departments.append("<option value="" + departments[i].id + "">" + departments[i].value + "</option>");
}

getManagers();

$departments.on("change", function(){
    getManagers();
});

I have hard-coded the department and manager sources as I don’t have a database.

Leave a Comment