cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
                  <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="f8be0591-a46e-11e7-86a2-d3ea1b9dd115">Animal</option>
                  <option value="ebaedcbe-a46f-11e7-86a2-fbad634de3c2">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> JSON Blob</h4>
          <p>The list data is serving here from <a href="https://jsonblob.com/" target="_blank">JSON Blob</a>. Thanks to JSON Blob!</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 -->
            
          
!
            
              /* 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;
  }
}
            
          
!
            
              /**
 * 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' };
    var apiUrl = 'https://jsonblob.com/api/category/:parentId:';
    
    $('select').select2(select2Options);                 
    var cascadLoading = new Select2Cascade($('#type'), $('#subtype'), apiUrl, select2Options);
    cascadLoading.then( function(parent, child, items) {
        // Dump response data
        console.log(items);
    });
});


            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console