Dynamic Cascading Dropdown Bootstrap

Dynamic Cascading Dropdown Bootstrap
Code Snippet:Select2 Dependent / Cascading Select List
Author: Anis uddin Ahmad
Published: 11 hours ago
Last Updated: November 7, 2025
Downloads: 4
License: MIT
Edit Code online: View on CodePen
Read More

This tutorial will guide you through the process of creating a Dynamic Cascading Dropdown Bootstrap form using Select2. Cascading dropdowns allow you to create dependent select boxes where the options in one dropdown are determined by the selection in another. This guide provides a clear, step-by-step approach to implementing this functionality.

Add Header Assets

To start, you will need to include the necessary CSS and meta tags in the “ section of your HTML document. This includes Bootstrap for styling, Select2 for enhanced select boxes, and Select2 Bootstrap CSS for theme compatibility.

<meta name="viewport" content="width=device-width, initial-scale=1"><link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-css/1.4.6/select2-bootstrap.min.css'>

Create HTML Structure

Next, you’ll create the basic HTML structure for your dynamic cascading dropdown form. This includes the container, header, and the select elements for the cascading dropdowns. We will create two dropdowns to keep this example easy to follow.

    <div class="container">
      <div class="header clearfix">
        <h3 class="text-muted">
          Select2 Cascade Demo
          <small>For <a href="http://ajaxray.com/blog/select2-dependent-cascading-select-list-reload/" target="_blank">this post</a></small>
        </h3>
      </div>

      <div class="row">
        <div class="col-sm-12">
          <p class="lead">Making Select2 (4.x) list boxes cascading / dependent.</p>
          <p>That means, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box. Let's try it -</p>
          
          <form class="form-horizontal">
            <div class="form-group">
              <label for="type" class="col-sm-5 control-label">I'd like to ride</label>   
              <div class="col-sm-5">
                <select name="type" id="type" class="form-control">
                  <option>--Select your ride--</option>
                  <option value="animals">Animal</option>
                  <option value="vehicles">Vehicle</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label for="subtype" class="col-sm-5 control-label">More specifically</label>       
              <div class="col-sm-5">
                <select name="subtype" id="subtype"  class="form-control">
                    <option>-- Select type first--</option>
                </select>
              </div>
            </div>         
          </form>        
      
        </div>
      </div>
      
      <div class="row marketing">
        <div class="col-lg-6">
          <h4><span class="glyphicon glyphicon-cloud-download"></span> Get the code</h4>
          <p>The source code is available as a <a href="https://gist.github.com/ajaxray/187e7c9a00666a7ffff52a8a69b8bf31" target="_blank">public gist</a>. Don't forget to <b><span class="glyphicon glyphicon-star"></span> it!</b></p>
         
          <h4><span class="glyphicon glyphicon-thumbs-up"></span> Raw gist</h4>
          <p>The list data is serving here from <a href="https://gist.github.com/ajaxray/32c5a57fafc3f6bc4c430153d66a55f5" target="_blank">a secret gist</a>. Just using the raw version of files to get the JSON.</p>
        </div>

        <div class="col-lg-6">
          <h4><span class="glyphicon glyphicon-eye-open"></span> Behind the scene</h4>
          <p>You may keep an eye on browser console to check the requests and response data.</p>

          <h4><span class="glyphicon glyphicon-ok"></span> Twitter Bootstrap</h4>
          <p>This demo is using <a href="https://getbootstrap.com/" target="_blank"> Twitter Bootstrap</a>, my first choice of CSS Frameworks.</p>


        </div>
      </div>

      <footer class="footer">
        <p>&copy; 2017 <a href="http://ajaxray.com" target="_blank">ajaxray.com</a>.</p>
      </footer>

    </div> <!-- /container -->

Add CSS Styles

To make the form visually appealing and responsive, you can add custom CSS styles. These styles will handle the layout and appearance of the form elements.

/* Space out content a bit */
body {
  padding-top: 20px;
  padding-bottom: 20px;
}

/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
  padding-right: 15px;
  padding-left: 15px;
}

/* Custom page header */
.header {
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
}
/* Make the masthead heading the same height as the navigation */
.header h3 {
  margin-top: 0;
  margin-bottom: 0;
  line-height: 40px;
}

/* Custom page footer */
.footer {
  padding-top: 19px;
  color: #777;
  border-top: 1px solid #e5e5e5;
}

/* Customize container */
@media (min-width: 768px) {
  .container {
    max-width: 730px;
  }
}
.container-narrow > hr {
  margin: 30px 0;
}

/* Supporting marketing content */
.marketing {
  margin: 40px 0;
}
.marketing p + h4 {
  margin-top: 28px;
}

/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  /* Remove the padding we set earlier */
  .header,
  .marketing,
  .footer {
    padding-right: 0;
    padding-left: 0;
  }
  /* Space out the masthead */
  .header {
    margin-bottom: 30px;
  }
  /* Remove the bottom border on the jumbotron for visual effect */
  .jumbotron {
    border-bottom: 0;
  }
}

Implement JavaScript Functionality

To enable the dynamic cascading behavior, you’ll need to add JavaScript code using jQuery and Select2. This script will handle the AJAX requests to load the options for the child select box based on the selected value of the parent select box.

/**
 * A Javascript module to loadeding/refreshing options of a select2 list box using ajax based on selection of another select2 list box.
 * 
 * @url : https://gist.github.com/ajaxray/187e7c9a00666a7ffff52a8a69b8bf31
 * @auther : Anis Uddin Ahmad <anis.programmer@gmail.com>
 * 
 * Live demo - https://codepen.io/ajaxray/full/oBPbQe/
 * w: http://ajaxray.com | t: @ajaxray
 */
var Select2Cascade = ( function(window, $) {

    function Select2Cascade(parent, child, url, select2Options) {
        var afterActions = [];
        var options = select2Options || {};

        // Register functions to be called after cascading data loading done
        this.then = function(callback) {
            afterActions.push(callback);
            return this;
        };

        parent.select2(select2Options).on("change", function (e) {

            child.prop("disabled", true);

            var _this = this;
            $.getJSON(url.replace(':parentId:', $(this).val()), function(items) {
                var newOptions = '<option value="">-- Select --</option>';
                for(var id in items) {
                    newOptions += '<option value="'+ id +'">'+ items[id] +'</option>';
                }

                child.select2('destroy').html(newOptions).prop("disabled", false)
                    .select2(options);
                
                afterActions.forEach(function (callback) {
                    callback(parent, child, items);
                });
            });
        });
    }

    return Select2Cascade;

})( window, $);

$(document).ready(function() {
    var select2Options = { width: 'resolve' };
    // Loading raw JSON files of a secret gist - https://gist.github.com/ajaxray/32c5a57fafc3f6bc4c430153d66a55f5
    var apiUrl =  'https://gist.githubusercontent.com/ajaxray/32c5a57fafc3f6bc4c430153d66a55f5/raw/260a653e6347fb6d2360e8ec376a2dc4888c1afa/:parentId:.json'; 
    
    $('select').select2(select2Options);                 
    var cascadLoading = new Select2Cascade($('#type'), $('#subtype'), apiUrl, select2Options);
    cascadLoading.then( function(parent, child, items) {
        // Dump response data
        console.log(items);
    });
});

Add Footer Assets

If you have any Javascript libraries which are not important on initial page load, you can place them here.

That’s all! Hopefully, you have successfully created a Dynamic 5 Cascading Dropdown Bootstrap form using Select2. If you have any questions or suggestions, feel free to comment below.

Related posts:

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.