具有列过滤器下拉列表和多个复选框选择的数据表 [英] Datatables with column filter dropdowns and multiple checkbox selection

查看:31
本文介绍了具有列过滤器下拉列表和多个复选框选择的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从joao vitor retamero-小提琴中找到了这个出色的代码: https://jsfiddle.net/jvretamero/bv6g0r64/展示了如何在jquery数据表列过滤器中进行多项选择.但是我需要将过滤器容器转换为下拉菜单,容器中的每个项目都是一个复选框.是的,正如我在几个小时的研究中发现的那样,对此有很多参考.但是我还没有找到任何示例,也没有找到关于如何执行此操作的任何清晰解释,尽管许多人说使用jquery插件是可能的.任何人都可以指出任何例子吗?我不知道如何开始.非常感谢.

 < script src ="https://code.jquery.com/jquery-1.12.4.js"></script>< script src ="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"</script>< script src ="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"</script>$(document).ready(function(){$('#example').DataTable({initComplete:function(){this.api().columns().every(function(){var column = this;var select = $('< select multiple ="multiple">< option value ="></option></select>').appendTo($(column.footer()).empty()).on('change',function(){var vals = $('option:selected',this).map(function(index,element){返回$ .fn.dataTable.util.escapeRegex($(element).val());}).toArray().join('|');柱子.search(vals.length> 0?'^('+ vals +')$':'',true,false).画();});column.data().unique().sort().each(function(d,j){select.append('< option value ='+ d +'">'+ d +'</option>')});});}});}); 

解决方案

尝试一下,它不使用任何额外的JS/jQuery库:

 //此代码已通过http://jsbeautifier.org/进行了美化,带有2个空格的缩进.$(document).ready(function(){函数cbDropdown(column){返回$('< ul>'',{'class':'cb-dropdown'}).appendTo($('< div>',{'class':'cb-dropdown-wrap'}).appendTo(column));}$('#example').DataTable({initComplete:function(){this.api().columns().every(function(){var column = this;var ddmenu = cbDropdown($(column.header())).on('change',':checkbox',function(){var active;var vals = $(':checked',ddmenu).map(function(index,element){active = true;返回$ .fn.dataTable.util.escapeRegex($(element).val());}).toArray().join('|');柱子.search(vals.length> 0?'^('+ vals +')$':'',true,false).画();//高亮显示当前项目(如果选中).如果(已检查){$(this).closest('li').addClass('active');} 别的 {$(this).closest('li').removeClass('active');}//突出显示当前过滤器(如果已选中).var active2 = ddmenu.parent().is('.active');if(active&&!active2){ddmenu.parent().addClass('active');} else if(!active&&active2){ddmenu.parent().removeClass('active');}});column.data().unique().sort().each(function(d,j){var//包装$ label = $('< label>'),$ text = $('< span>',, {文字:d}),$ cb = $('< input>',{类型:复选框",值:d});$ text.appendTo($ label);$ cb.appendTo($ label);ddmenu.append($('< li>').append($ label));});});}});}); 

CSS

 /*下拉菜单的样式.随意更改样式以适合您的网站.:-) */.cb-dropdown-wrap {max-height:80像素;/*最多约有3/4个可见项目.*/职位:相对高度:19像素;}.cb-dropdown,.cb-dropdown li {边距:0;填充:0;列表样式:无;}.cb-dropdown {位置:绝对;z索引:1;宽度:100%;高度:100%;溢出:隐藏;背景:#fff;边框:1px实线#888;}/*对于选定的过滤器.*/.active .cb-dropdown {背景:粉红色;}.cb-dropdown-wrap:hover .cb-dropdown {高度:80px;溢出:自动;过渡:0.2s高度缓入与缓出;}/*对于选定的项目.*/.cb-dropdown li.active {背景:#ff0;}.cb-dropdown li标签{显示:块;职位:相对光标:指针;行高:19px;/* .cb-dropdown-wrap的匹配高度*/}.cb-dropdown li标签>输入 {位置:绝对;正确:0;最高:0;宽度:16像素;}.cb-dropdown li标签>跨度 {显示:块;左边距:3px;右边距:20px;/*至少是复选框的宽度.*/字体家族:sans-serif;字号:0.8em;字体粗细:正常;文字对齐:左;}/*这可以修复排序图标的垂直对齐.*/table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc_disabled {背景位置:100%10px;} 

演示

https://jsfiddle.net/41vgefnf/1/
https://jsfiddle.net/41vgefnf/6/
https://jsfiddle.net/41vgefnf/8/
https://jsfiddle.net/41vgefnf/9/
https://jsfiddle.net/41vgefnf/10/

更新

我将过滤器下拉列表移至标题,并设置了下拉菜单的样式,使其看起来更像下拉菜单.(下拉功能中不涉及JS或jQuery ;仅具有基本动画的纯CSS— CSS3 transition .)

更新#2

对不起,我忘了将CSS活动"的 class 应用于所选项目.

更新#3

Update#2 情况相同,但下拉菜单包装器相同.(很抱歉忘记了这些事情.我只是为了符合/满足您实际要求的要求/变更进行了编辑.:) 但我认为此更新将是最终修订版.)

更新#4

修复了下拉菜单包装的有效"状态更改.

信用

感谢@Giacomo提供的小提琴.=)

I found this excellent code from joao vitor retamero - fiddle: https://jsfiddle.net/jvretamero/bv6g0r64/ that shows how to make multiple selections in jquery datatable column filters. But I need to transform the filter containers into dropdowns, with each item in the container being a checkbox. Yes, there are many references to this, as I've found out during several hours of researching. But I'm yet to find any examples, or any clear explanations of how to do this, despite many saying it's possible with jquery plugin. Can anyone point to any examples? I've no clue how to even start. Many thanks.

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"></script>

    $(document).ready(function() {
    $('#example').DataTable( {
        initComplete: function () {
            this.api().columns().every( function () {
                var column = this;
                var select = $('<select multiple="multiple"><option value=""></option></select>')
                    .appendTo( $(column.footer()).empty() )
                    .on( 'change', function () {
                        var vals = $('option:selected', this).map(function (index, element) {
                            return $.fn.dataTable.util.escapeRegex($(element).val());
                        }).toArray().join('|');

                        column
                            .search( vals.length > 0 ? '^('+vals+')$' : '', true, false )
                            .draw();
                    } );

                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                } );
            } );
        }
    } );
} );

解决方案

Try this, which doesn't use any extra JS/jQuery libraries:

// This code has been beautified via http://jsbeautifier.org/ with 2 spaces indentation.
$(document).ready(function() {
  function cbDropdown(column) {
    return $('<ul>', {
      'class': 'cb-dropdown'
    }).appendTo($('<div>', {
      'class': 'cb-dropdown-wrap'
    }).appendTo(column));
  }

  $('#example').DataTable({
    initComplete: function() {
      this.api().columns().every(function() {
        var column = this;
        var ddmenu = cbDropdown($(column.header()))
          .on('change', ':checkbox', function() {
            var active;
            var vals = $(':checked', ddmenu).map(function(index, element) {
              active = true;
              return $.fn.dataTable.util.escapeRegex($(element).val());
            }).toArray().join('|');

            column
              .search(vals.length > 0 ? '^(' + vals + ')$' : '', true, false)
              .draw();

            // Highlight the current item if selected.
            if (this.checked) {
              $(this).closest('li').addClass('active');
            } else {
              $(this).closest('li').removeClass('active');
            }

            // Highlight the current filter if selected.
            var active2 = ddmenu.parent().is('.active');
            if (active && !active2) {
              ddmenu.parent().addClass('active');
            } else if (!active && active2) {
              ddmenu.parent().removeClass('active');
            }
          });

        column.data().unique().sort().each(function(d, j) {
          var // wrapped
            $label = $('<label>'),
            $text = $('<span>', {
              text: d
            }),
            $cb = $('<input>', {
              type: 'checkbox',
              value: d
            });

          $text.appendTo($label);
          $cb.appendTo($label);

          ddmenu.append($('<li>').append($label));
        });
      });
    }
  });
});

CSS

/* Styles for the drop-down. Feel free to change the styles to suit your website. :-) */

.cb-dropdown-wrap {
  max-height: 80px; /* At most, around 3/4 visible items. */
  position: relative;
  height: 19px;
}

.cb-dropdown,
.cb-dropdown li {
  margin: 0;
  padding: 0;
  list-style: none;
}

.cb-dropdown {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  border: 1px solid #888;
}

/* For selected filter. */
.active .cb-dropdown {
  background: pink;
}

.cb-dropdown-wrap:hover .cb-dropdown {
  height: 80px;
  overflow: auto;
  transition: 0.2s height ease-in-out;
}

/* For selected items. */
.cb-dropdown li.active {
  background: #ff0;
}

.cb-dropdown li label {
  display: block;
  position: relative;
  cursor: pointer;
  line-height: 19px; /* Match height of .cb-dropdown-wrap */
}

.cb-dropdown li label > input {
  position: absolute;
  right: 0;
  top: 0;
  width: 16px;
}

.cb-dropdown li label > span {
  display: block;
  margin-left: 3px;
  margin-right: 20px; /* At least, width of the checkbox. */
  font-family: sans-serif;
  font-size: 0.8em;
  font-weight: normal;
  text-align: left;
}

/* This fixes the vertical aligning of the sorting icon. */
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
  background-position: 100% 10px;
}

Demo

https://jsfiddle.net/41vgefnf/1/
https://jsfiddle.net/41vgefnf/6/
https://jsfiddle.net/41vgefnf/8/
https://jsfiddle.net/41vgefnf/9/
https://jsfiddle.net/41vgefnf/10/

UPDATE

I moved the filter dropdowns to the header, and styled the dropdowns to look more like dropdown menus. (No JS or jQuery involved in the dropdown functionality; just pure CSS with basic animation — CSS3 transition.)

UPDATE #2

Sorry, I forgot apply the CSS "active" class to selected items.

UPDATE #3

Same like Update #2 case, but for the dropdown menu wrapper. (Sorry for keep forgetting things.. and I edited just to conform/meet to the requirements/changes you've actually requested. :) But I think this update would be the final revision.)

UPDATE #4

Fixed the "active" state change of the dropdown menu wrapper.

CREDITS

Thank you @Giacomo for your Fiddle. =)

这篇关于具有列过滤器下拉列表和多个复选框选择的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆