select2 3.5.3 二級下拉及搜索

select2 [3.5.3]版本git

select2 插件地址 http://select2.github.io/select2/github



支持搜索:
this

JS代碼,若是Group不須要勾選,goup不加id就能夠了。若是須要三級,能夠在二級的基礎上作修改。google

代碼是當時在google上搜到的。不記得是哪裏的了。spa

var arr = [
  {
    "text": "Group1",
    "id": "001",
    "children": [
      {
        "id": "001-1",
        "text": "member1-1",
      }
    ]
  },
  {
    "text": "Group2",
    "id": "002",
    "children": [
      {
        "id": "002-1",
        "text": "member2-1",
      },
      {
        "id": "002-2",
        "text": "member2-2",
      }
    ]
  },
  {
    "text": "Group3",
    "id": "003",
    "children": [
      {
        "id": "003-1",
        "text": "member3-1",
      },
      {
        "id": "003-2",
        "text": "member3-2",
      },
      {
        "id": "003-3",
        "text": "member3-3",
      }
    ]
  }
];

$(".group-select").select2({
    placeholder: "Select group or member",
    allowClear:true,
    data: arr,
    query: function (options){
        var selectedIds = options.element.select2('val');
        var data = jQuery.extend(true, {}, this.data);
        var selectableGroups = $.map(data, function (group) {
            var areAllChildrenSelected = true,
                parentMatchTerm = false,
                anyChildMatchTerm = false;
            if (group.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0) {
                parentMatchTerm = true;
            }
            var i = group.children.length;
            while (i--) {
                var child = group.children[i];
                if (selectedIds.indexOf(child.id) < 0) {
                    areAllChildrenSelected = false;
                }
                if (options.term == '' || (child.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0)) {
                    anyChildMatchTerm = true;
                }
                else if (!parentMatchTerm) {
                    var index = group.children.indexOf(child);
                    if (index > -1) {
                        group.children.splice(index, 1);
                    }
                }
            }
            return (!areAllChildrenSelected && (parentMatchTerm || anyChildMatchTerm)) ? group : null;
        });
        options.callback({ results: selectableGroups });
    }
});
相關文章
相關標籤/搜索