Click here to Skip to main content
15,886,095 members
Articles / Web Development / HTML
Tip/Trick

Working With JQX Grid With Filtering And Sorting

Rate me:
Please Sign up or sign in to vote.
4.89/5 (19 votes)
16 Oct 2014CPOL2 min read 50.2K   461   22   23
Working With JQX Grid With Filtering And Sorting

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

We all worked with JQ Grid. Today i got a requirement of implementing JQX Grid in my web application. If you are new to JQ Grid you can read here : http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-NET . Here i am gonna explain the steps to implement the JQX Grid in our application.

What you must know?

  1. Jquery : http://jquery.com/
  2. Javascript : http://www.w3schools.com/js/
  3. CSS 3 : http://www.w3schools.com/css/css3_intro.asp
  4. HTML : http://www.w3schools.com/html/
  5. DOM Manipulations in JQuery : http://www.tutorialspoint.com/jquery/jquery-dom.htm

Background

We can implement the JQX Grid in MVC and in our web application. You can find the demo here : http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm#demos/jqxgrid/filterconditions.htm .

You can download the needed file from http://www.jqwidgets.com/download/ .

What made me to choose JQX Grid?

The answer is simple. We have so many clien side grid providers (JQGrid,Telerik,JQX etc..... If you are not aware of those , please have a look at here http://www.sitepoint.com/10-jquery-grids/ . But in my requirement clent needs a toggle panel in which the filtering conditions occurs. When i searched , JQX Grid was the one with better performance. (Some others also supports the same features, but it was little bit slow.).

Using the code

There are some steps that we must follow to implement the JQX in our application. 

Step 1: Download all the needed files

Step 2: Create a new web application .

 Image 1

Step 3: Add the selected folders to your application

Image 2

Step 4: Add a new page

HTML
<!DOCTYPE html>
<html lang="en">
<head>   
</head>
<body >
    
</body>
</html>

Step 5: Add the stylesheets and needed js files .

HTML
<link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxdata.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxbuttons.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxscrollbar.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxlistbox.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxdropdownlist.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxmenu.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxgrid.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxgrid.filter.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxgrid.sort.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxgrid.selection.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxpanel.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxcheckbox.js"></script>
    <script type="text/javascript" src="scripts/demos.js"></script>

(Make sure that you add the js files in order)

Step 6: Create the DOM elements in which you want to show the JQX Grid

HTML
<div id='jqxWidget' style="font-size: 13px; font-family: Verdana; float: left;">
       <div id="jqxgrid">
       </div>
   </div>

Step 7: Generate some dynamic json data , so that you can generate the JQX Grid easily . You can take the data from the database and convert it to the JSON. If you are new to the json converting ways, you can get it here: https://www.nuget.org/packages/newtonsoft.json/

If you are not aware of how to add the newtonsoft and use, please see this video. And please dont forget to rate his video. He has done good job :) .

https://www.youtube.com/watch?v=76blDatESaA

Here I am generating data dynamically in JS file. Please find the generatedata.js file in the bundle of JQX Grid. Please add this to your script section.

HTML
<script src="generatedata.js" type="text/javascript"></script>

If you go into the generatedata.js, you can see a function generatedata, which is for creating the datas

(Json)dynamically .

JavaScript
function generatedata(rowscount, hasNullValues) {
    // prepare the data
    var data = new Array();
    if (rowscount == undefined) rowscount = 100;
    var firstNames =
    [
        "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
    ];

    var lastNames =
    [
        "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"
    ];

    var productNames =
    [
        "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", "Caffe Latte", "White Chocolate Mocha", "Caramel Latte", "Caffe Americano", "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
    ];

    var priceValues =
    [
         "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
    ];

    for (var i = 0; i < rowscount; i++) {
        var row = {};
        var productindex = Math.floor(Math.random() * productNames.length);
        var price = parseFloat(priceValues[productindex]);
        var quantity = 1 + Math.round(Math.random() * 10);

        row["id"] = i;
        row["available"] = productindex % 2 == 0;
        if (hasNullValues == true) {
            if (productindex % 2 != 0) {
                var random = Math.floor(Math.random() * rowscount);
                row["available"] = i % random == 0 ? null : false;
            }
        }
        row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
        row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];
        row["name"] = row["firstname"] + " " + row["lastname"];
        row["productname"] = productNames[productindex];
        row["price"] = price;
        row["quantity"] = quantity;
        row["total"] = price * quantity;

        var date = new Date();
        date.setFullYear(2014, Math.floor(Math.random() * 12), Math.floor(Math.random() * 27));
        date.setHours(0, 0, 0, 0);
        row["date"] = date;
       
        data[i] = row;
    }

    return data;
}

Step 8: Now here is the main part. Add the main code to your script tag in the page. Here we are appending the Grid to the element which has id as jqxgrid.

JavaScript
<script type="text/javascript">
        $(document).ready(function () {
            var data = generatedata(500);
            var source =
            {
                localdata: data,
                datafields:
                [
                    { name: 'firstname', type: 'string' },
                    { name: 'lastname', type: 'string' },
                    { name: 'productname', type: 'string' },
                    { name: 'date', type: 'date' },
                    { name: 'quantity', type: 'number' }
                ],
                datatype: "array"
            };

            var addfilter = function () {
                var filtergroup = new $.jqx.filter();

                var filter_or_operator = 1;
                var filtervalue = 'Beate';
                var filtercondition = 'contains';
                var filter1 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);

                filtervalue = 'Andrew';
                filtercondition = 'contains';
                var filter2 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);

                filtergroup.addfilter(filter_or_operator, filter1);
                filtergroup.addfilter(filter_or_operator, filter2);
                // add the filters.
                $("#jqxgrid").jqxGrid('addfilter', 'firstname', filtergroup);
                // apply the filters.
                $("#jqxgrid").jqxGrid('applyfilters');
            }
            var dataAdapter = new $.jqx.dataAdapter(source);

            $("#jqxgrid").jqxGrid(
            {
                width: 850,
                source: dataAdapter,
                filterable: true,
                sortable: true,
                autoshowfiltericon: true,
                ready: function () {
                    addfilter();
                    var localizationObject = {
                        filterstringcomparisonoperators: ['contains', 'does not contain'],
                        // filter numeric comparison operators.
                        filternumericcomparisonoperators: ['less than', 'greater than'],
                        // filter date comparison operators.
                        filterdatecomparisonoperators: ['less than', 'greater than'],
                        // filter bool comparison operators.
                        filterbooleancomparisonoperators: ['equal', 'not equal']
                    }
                    $("#jqxgrid").jqxGrid('localizestrings', localizationObject);
                },
                updatefilterconditions: function (type, defaultconditions) {
                    var stringcomparisonoperators = ['CONTAINS', 'DOES_NOT_CONTAIN'];
                    var numericcomparisonoperators = ['LESS_THAN', 'GREATER_THAN'];
                    var datecomparisonoperators = ['LESS_THAN', 'GREATER_THAN'];
                    var booleancomparisonoperators = ['EQUAL', 'NOT_EQUAL'];
                    switch (type) {
                        case 'stringfilter':
                            return stringcomparisonoperators;
                        case 'numericfilter':
                            return numericcomparisonoperators;
                        case 'datefilter':
                            return datecomparisonoperators;
                        case 'booleanfilter':
                            return booleancomparisonoperators;
                    }
                },
                updatefilterpanel: function (filtertypedropdown1, filtertypedropdown2, filteroperatordropdown, filterinputfield1, filterinputfield2, filterbutton, clearbutton,
                 columnfilter, filtertype, filterconditions) {
                    var index1 = 0;
                    var index2 = 0;
                    if (columnfilter != null) {
                        var filter1 = columnfilter.getfilterat(0);
                        var filter2 = columnfilter.getfilterat(1);
                        if (filter1) {
                            index1 = filterconditions.indexOf(filter1.comparisonoperator);
                            var value1 = filter1.filtervalue;
                            filterinputfield1.val(value1);
                        }

                        if (filter2) {
                            index2 = filterconditions.indexOf(filter2.comparisonoperator);
                            var value2 = filter2.filtervalue;
                            filterinputfield2.val(value2);
                        }
                    }

                    filtertypedropdown1.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index1 });
                    filtertypedropdown2.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index2 });
                },
                columns: [
                  { text: 'First Name', datafield: 'firstname', width: 200 },
                  { text: 'Last Name', datafield: 'lastname', width: 200 },
                  { text: 'Product', datafield: 'productname', width: 180 },
                  { text: 'Order Date', datafield: 'date', width: 160, cellsformat: 'dd-MMMM-yyyy' },
                  { text: 'Quantity', datafield: 'quantity', cellsalign: 'right' }
                ]
            });

            $('#events').jqxPanel({ width: 300, height: 80});

            $("#jqxgrid").on("filter", function (event) {
                $("#events").jqxPanel('clearcontent');
                var filterinfo = $("#jqxgrid").jqxGrid('getfilterinformation');

                var eventData = "Triggered 'filter' event";
                for (i = 0; i < filterinfo.length; i++) {
                    var eventData = "Filter Column: " + filterinfo[i].filtercolumntext;
                    $('#events').jqxPanel('prepend', '<div style="margin-top: 5px;">' + eventData + '</div>');
                }
            });

            $('#clearfilteringbutton').jqxButton({ theme: theme });
            $('#filterbackground').jqxCheckBox({ checked: true, height: 25});
            $('#filtericons').jqxCheckBox({ checked: false, height: 25});
            // clear the filtering.
            $('#clearfilteringbutton').click(function () {
                $("#jqxgrid").jqxGrid('clearfilters');
            });
            // show/hide filter background
            $('#filterbackground').on('change', function (event) {
                $("#jqxgrid").jqxGrid({ showfiltercolumnbackground: event.args.checked });
            });
            // show/hide filter icons
            $('#filtericons').on('change', function (event) {
                $("#jqxgrid").jqxGrid({ autoshowfiltericon: !event.args.checked });
            });
        });
    </script>

Step 9: Now build and run your code , you will get output as the following .

Image 3

Have a happy coding :)

History

First version on: 13-Oct-2014 10:30 PM.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionGood Article Pin
Santhakumar Munuswamy @ Chennai15-Aug-15 1:06
professionalSanthakumar Munuswamy @ Chennai15-Aug-15 1:06 
GeneralGreat Article Pin
Ganesh Nellaiappan Rajan8-Nov-14 0:49
Ganesh Nellaiappan Rajan8-Nov-14 0:49 
GeneralRe: Great Article Pin
Sibeesh KV8-Nov-14 1:11
professionalSibeesh KV8-Nov-14 1:11 
QuestionNice Work Pin
Member 938105329-Oct-14 6:38
Member 938105329-Oct-14 6:38 
AnswerRe: Nice Work Pin
Sibeesh KV29-Oct-14 6:41
professionalSibeesh KV29-Oct-14 6:41 
QuestionMy vote of 5 Pin
Member 1117423926-Oct-14 23:37
Member 1117423926-Oct-14 23:37 
AnswerRe: My vote of 5 Pin
Sibeesh KV26-Oct-14 23:40
professionalSibeesh KV26-Oct-14 23:40 
QuestionExcellent Article Pin
Murali Muthusamy22-Oct-14 21:00
Murali Muthusamy22-Oct-14 21:00 
AnswerRe: Excellent Article Pin
Sibeesh KV22-Oct-14 21:02
professionalSibeesh KV22-Oct-14 21:02 
Answercomment Pin
Annamalai0922-Oct-14 20:53
Annamalai0922-Oct-14 20:53 
GeneralRe: comment Pin
Sibeesh KV22-Oct-14 20:54
professionalSibeesh KV22-Oct-14 20:54 
GeneralExcellent Work Pin
Shanto Thomas22-Oct-14 3:30
Shanto Thomas22-Oct-14 3:30 
GeneralRe: Excellent Work Pin
Sibeesh KV22-Oct-14 3:45
professionalSibeesh KV22-Oct-14 3:45 
SuggestionGithub Pin
mmuekk2321-Oct-14 11:24
mmuekk2321-Oct-14 11:24 
GeneralRe: Github Pin
Sibeesh KV21-Oct-14 17:19
professionalSibeesh KV21-Oct-14 17:19 
QuestionIt is very help full,,,,,Thank u Pin
Asaru vellat18-Oct-14 3:02
Asaru vellat18-Oct-14 3:02 
AnswerRe: It is very help full,,,,,Thank u Pin
Sibeesh KV18-Oct-14 3:03
professionalSibeesh KV18-Oct-14 3:03 
QuestionOne question Pin
Tridip Bhattacharjee16-Oct-14 21:09
professionalTridip Bhattacharjee16-Oct-14 21:09 
AnswerRe: One question Pin
Sibeesh KV16-Oct-14 23:43
professionalSibeesh KV16-Oct-14 23:43 
AnswerRe: One question Pin
Sibeesh KV16-Oct-14 23:44
professionalSibeesh KV16-Oct-14 23:44 
AnswerRe: One question Pin
Sibeesh KV21-Oct-14 5:52
professionalSibeesh KV21-Oct-14 5:52 
QuestionReally Nice Pin
Suraj Sahoo | Coding Passion16-Oct-14 7:25
professionalSuraj Sahoo | Coding Passion16-Oct-14 7:25 
AnswerRe: Really Nice Pin
Sibeesh KV16-Oct-14 7:29
professionalSibeesh KV16-Oct-14 7:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.