select2 3.5.3 二级下拉及搜索

select2 [3.5.3]版本

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



支持搜索:

JS代码,如果Group不需要勾选,goup不加id就可以了。如果需要三级,可以在二级的基础上做修改。

代码是当时在google上搜到的。不记得是哪里的了。

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 });
    }
});

 

posted @ 2017-12-05 15:42  萌面猫  阅读(3440)  评论(0编辑  收藏  举报