Book Image

HTML5 Data and Services Cookbook

Book Image

HTML5 Data and Services Cookbook

Overview of this book

HTML5 is everywhere. From PCs to tablets to smartphones and even TVs, the web is the most ubiquitous application platform and information medium bar. Its becoming a first class citizen in established operating systems such as Microsoft Windows 8 as well as the primary platform of new operating systems such as Google Chrome OS. "HTML5 Data and Services Cookbook" contains over 100 recipes explaining how to utilize modern features and techniques when building websites or web applications. This book will help you to explore the full power of HTML5 - from number rounding to advanced graphics to real-time data binding. "HTML5 Data and Services Cookbook" starts with the display of text and related data. Then you will be guided through graphs and animated visualizations followed by input and input controls. Data serialization, validation and communication with the server as well as modern frameworks with advanced features like automatic data binding and server communication will also be covered in detail.This book covers a fast track into new libraries and features that are part of HTML5!
Table of Contents (21 chapters)
HTML5 Data and Services Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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/.