官术网_书友最值得收藏!

Creating combined complex filters

When displaying tables, we sometimes want to filter table elements using multiple criteria involving multiple columns. For example, given a table of people that contains information such as their name, age, and transportation method, we might only want to view the people older than 30 that use a bus for transportation. We might also want to filter people by name. To do this, we have to apply multiple filters, such as an age range filter, a multiple-choice filter, and a text filter, to the data at the same time. The easiest way to do this is to make a filter combination function.

Getting ready

We're going to assume that we're using the code from the Creating a sortable paginated table recipe, and we're going to add our filters as described in the previous two recipes. This time we're going to allow for the combination of filters.

How to do it...

Let's modify the previous code to add multiple filters to our table:

  1. We're going to add filter-related inputs to our page after the opening <body> tag:
    <select id="list" style="width:100px;"  multiple>
    </select>
    Age: <input id="range1" type="text">
    to <input id="range2" type="text">,
    Name: <input type="text" id="name"> <br>
  2. Add the filter.js script before the closing </body> tag:
    <script type="text/javascript" src="filter.js"></script>
  3. We're going to modify example.js to fetch data after the page is loaded and trigger a table:data event after displaying the data:
        $(function() {
            fetchData(function(data) {
                window.myTable.data = data;
                setData(data);
                $("#demo").trigger("table:data");
            });
        });
  4. Then we can create filter.js by combining the code from the previous two recipes:
    (function() {
        function getUnique(data, column) {
            var unique = [];
            data.forEach(function(row) {
                if (unique.indexOf(row[column]) < 0)
                    unique.push(row[column]);
            });
            return unique;
        }
        function choiceFilter(valueList, col) {
            return function filter(el) {
                return valueList.indexOf(el[col]) >= 0;
            }
        }
        function number(n, def) {
            if (n == '') return def;
            n = new Number(n);
            if (isNaN(n)) return def;
            return n;
        }
        function rangeFilter(start, end, col) {
            var start = number(start, -Infinity),
                end = number(end, Infinity);
            return function filter(el) {
                return start < el[col] && el[col] < end;
            };
        }
        function textFilter(txt, col) {
            return function filter(el) {
                return el[col].indexOf(txt) >= 0;
            };
        }
        $("#demo").on('table:data', function() {
            getUnique(window.myTable.data, 4)
            .forEach(function(item) {
                $("<option />").attr('value', item)
                    .html(item).appendTo("#list");
            });
        });
        var filters = [null, null, null];
        $("#list").change(function() {
            filters[0] = choiceFilter($("#list").val(), 4);
            filterAndShow();
        });
        $("#range1,#range2").on('change keyup', function() {
            filters[1] = rangeFilter($("#range1").val(),
                $("#range2").val(), 2);
            filterAndShow();
        });
        $("#name").on('change keyup', function() {
            filters[2] = textFilter($("#name").val(), 1); filterAndShow();
        });
        function filterAndShow() {
            var filtered = window.myTable.data;
            filters.forEach(function(filter) {
                if (filter) filtered = filtered.filter(filter);
            });
            window.myTable.setData(filtered);
        };
    }());

How it works...

Like in the previous recipes, we use the Array.filter function to filter the table. This time we apply multiple filters in succession. We store all of the filter functions in an array.

Whenever there is a change in the inputs, we update the appropriate filter function and rerun filterAndShow() to display the filtered data.

There's more...

DataTables is a highly flexible table library with many options and a rich API. More information and examples can be found on the official website at http://www.datatables.net/.

主站蜘蛛池模板: 喀什市| 金堂县| 吕梁市| 遵义县| 德昌县| 宣恩县| 德庆县| 阳山县| 瑞昌市| 华蓥市| 安顺市| 四平市| 宜君县| 东莞市| 江源县| 昂仁县| 张家界市| 日照市| 龙口市| 玉屏| 定南县| 乐都县| 大连市| 宜良县| 丹东市| 濉溪县| 佳木斯市| 秦安县| 宜黄县| 秭归县| 桐梓县| 施甸县| 乐东| 大庆市| 庄河市| 集安市| 营口市| 鱼台县| 弋阳县| 永春县| 泰兴市|