Hello programmers! This is a new “JavaScript How To” post which describes ‘How to create Cascading Dropdown Using Plain JS’. This is an example of multiple dependent dropdown lists. Multiple dependent cascading dropdown lists are very useful when you want to display the data in specific categories. You can change drop down options based on another dropdown lists.

First of all, you can click on Try yourself button in below example and check what are we going to create and after that you will find all the require source code of this project. You can also bookmark the repository of progrramers GitHub community where you can find and download the source code of other projects.
If you like our posts please give thumbs up  👍 on our Facebook page and also share with your near n dears.



Diagram

In this example we are assuming that there is a school. It has multiple class rooms, every class room contains multiple sections, every section contains multiple subjects and at last every section period will held on a different room. You can see the whole scenario in below image given for the reference.

How to create Cascading Dropdown Using Plain JS - progrramers
How to create Cascading Dropdown Using Plain JS - progrramers

The data will be in tree structure which is used to parse as options in 'SELECT' elements. Let's see the work flow of the final product.

Work Flow 

  1. Classes names only append into select element onload first.
  2. When Selecting a Class then section options will append, available with that class. Same work flow for sections, subjects and rooms.
  3. When Class gets changed then sections, subjects and rooms also get reset. Same work flow for sections, subjects and rooms. Synopsis when a drop down element updated then all next siblings also gets reset.
Now you can copy the code and paste it into your favorite editor and save as ‘anyname.html’ and run into your favorite browser. Analyze the code and if you are getting any problem then feel free to write down into the comment section I’ll try to be more specific into the answers.

You can also get this code on github : How to create Cascading Dropdown Using Plain JS.html

How to create Cascading Dropdown Using Plain JS :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{box-sizing: border-box;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
        .classform{border: 5px groove #00acf0;background: #c5c5c5;border-radius: 4px;}
        div{padding:5px;}
        .classform>div{width:450px;display:block;margin-left:auto;margin-right:auto;}/*for responsive look*/
        label{background: #00acf0;color:rgb(255, 255, 255);text-shadow:1px 1px 1px #777}
        label,select{display:inline-block;padding:6px;border-radius:3px}
        label{width:100px;}
        select{width:250px;}
    </style>
</head>
<body>
    <div class="classform">
        <div><label for="class">Class: </label> <select name="class" id="class"></select></div>
        <div><label for="section">Section: </label> <select name="section" id="section"></select></div>
        <div><label for="subject">Subject: </label> <select name="subject" id="subject"></select></div>
        <div><label for="room">Room: </label> <select name="room" id="room"></select></div>
    </div><hr/>
    <a href="https://www.facebook.com/theprogrramers">Follow us on Facebook Page</a>
    <script>
        //class structure data in JS object format
        var structure = [
                {label:"class",value:"1",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                ]},
                {label:"class",value:"2",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Sanskrit",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"English",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Civics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Geography",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Economics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (C)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (D)",child:[]},
                        ]}
                    ]}
                ]},
                {label:"class",value:"3",child:[
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"3 (A)",child:[]},
                        ]}
                    ]}
                ]},
            ];
        //global variable declaration to store value stepwise
        var cindex, sindex, jindex;
        //calling funfction onload
        window.onload = function(){
            classstrucure(structure, document.querySelectorAll('[name=class]'));
        }
        document.querySelector('body').addEventListener('change',function(e){
            if(e.target.tagName.toLowerCase() == "select"){
                if(e.target.value!==""){
                    //check of nextsibling is null or not 
                    nextsibling = e.target.closest('DIV').nextSibling.nextSibling;
                    if(nextsibling!==null){
                        var _nameAttr=e.target.getAttribute("name");
                        var nextElm = nextsibling.querySelectorAll('SELECT');
                        //for your project only you have to change the attributes name
                        if(_nameAttr==='class'){
                            cindex = structure.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='section'){
                            sindex = structure[cindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='subject'){
                            jindex = structure[cindex].child[sindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child[jindex].child, nextElm);
                        }
                    }
                }else{
                    //e.target.value is empty then same function will fire with defferent parameters
                    clearsturcture(e.target.closest('DIV').nextSibling);
                }
            }
        });
        //function create the structure of class step wise
        function classstrucure(data, el){
            //first clear all the select element onload
            //clear all next sibling accept itself
            el.forEach(element => {
                clearsturcture(element.closest('DIV')); 
            });
           // clearsturcture(el[0].closest('DIV'));            
            var opt = '<option value="">--Select--</option>';
            //creating options elemnet
            for(var i=0;i<data.length;i++){
                opt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
            }
            //appending option on each element
            el.forEach(element => {
                element.innerHTML = opt;
            });
        }
        //clear all the next drop down element after itself
        function clearsturcture(parentEl){
            while (parentEl) {
                if(parentEl.tagName !== undefined){
                    //appending initial option on every next sibling
                    parentEl.querySelector('SELECT').innerHTML = '<option>--Select--</option>';
                }
                //looping through last existing sibling and target
                parentEl = parentEl.nextSibling;
            }
        }
    </script>
</body>
</html>
Try Yourself

Related Topics

progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

2 comments: