select2 3.5.3 二级下拉及搜索

2018-06-24 00:57:39来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:cookie、localStorage和sessionStorage区别

下一篇:react intl 国际化