首页 > 解决方案 > 将项目添加到 Select2 级联

问题描述

我的英语不是很好。对不起。

而且我不知道 Json 和 Ajax。

我想向Select2 Cascade添加两个以上的项目。

我又创建了一个选择/选项(#model),但它不起作用。

我在 json 文件夹中创建了三个文件: animal.json 、 Vehicles.json 、 horse.json

animal.json 和 Vehicles.json 文件运行和执行,但 horse.json 文件没有运行和执行。

当我选择马时,我希望第三个选择/选项(#model)支撑并打开。

我看到了以下页面,但我不明白。你能在这里修改或创建我的代码吗? http://ajaxray.com/blog/select2-dependent-cascading-select-list-reload/

我的 Json 文件如下:

{
"201" : "Horse",
"202" : "Elephant",
"203" : "Donkey",
"204" : "Camel",
"204" : "Tiger"
} 

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 =  'json/:parentId:.json';

    $('select').select2(select2Options);                 

    var cascadLoading = new Select2Cascade($('#type'), $('#subtype'), apiUrl, select2Options);
cascadLoading.then( function(parent, child, items) {
    // Open the child listbox immediately
    child.select2('open');
    // Dump response data
    console.log(items);
});
        var cascadLoading = new Select2Cascade($('#subtype'), $('#model'), apiUrl, select2Options);
cascadLoading.then( function(parent, child, items) {
    // Open the child listbox immediately
    child.select2('open');
    // Dump response data
    console.log(items);
});
     $('#subtype').prop('disabled', true);
     $('#model').prop('disabled', true);

});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Select2</title>
 <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    
<meta http-equiv="Pragma" content="no-cache">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-css/1.4.6/select2-bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

</head>
<body>
<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>
  <div class="form-group">
              <label for="model" class="col-sm-5 control-label">More specifically</label>       
              <div class="col-sm-5">
                <select name="model" id="model"  class="form-control">
                    <option>-- Select type first--</option>
                </select>
              </div>
            </div>           
          </form>
          </body></html>

标签: jqueryjsonajaxselectjquery-select2

解决方案


这是更改的代码。基于假设您需要第三项。通常id,只要代码中有重复,它就应该始终是唯一的id,它不适用于第二个。您必须id使用不同的代码或修改代码class

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://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) {
    // Open the child listbox immediately
    child.select2('open');
    // Dump response data
    console.log(items);
  });
  var cascadLoading = new Select2Cascade($('#subtype'), $('#model'), apiUrl, select2Options);
  cascadLoading.then(function(parent, child, items) {
    // Open the child listbox immediately
    child.select2('open');
    // Dump response data
    console.log(items);
  });
  var cascadLoading1 = new Select2Cascade($('#type'), $('#subtype_1'), apiUrl, select2Options);
  cascadLoading1.then(function(parent, child, items) {
    // Dump response data
    //console.log(items);
  });
  $('#subtype').prop('disabled', true);
  $('#subtype_1').prop('disabled', true);
  $('#model').prop('disabled', true);

});
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Select2</title>
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">

  <meta http-equiv="Pragma" content="no-cache">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-css/1.4.6/select2-bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

</head>

<body>
  <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>

    <div class="form-group">
      <label for="subtype" class="col-sm-5 control-label">More specifically 2</label>
      <div class="col-sm-5">
        <select name="subtype" id="subtype_1" class="form-control">
          <option>-- Select type first--</option>
        </select>
      </div>
    </div>
  </form>
</body>

</html>


推荐阅读