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

jQuery Datatables For Beginners

Rate me:
Please Sign up or sign in to vote.
4.85/5 (24 votes)
20 Nov 2014CPOL4 min read 186.4K   29   9
Simplest way to add Sorting, Filtering, Paging and many features to your plain HTML table

Introduction

In this tip, I'll explain how to have basic HTML table features like Sorting, Searching, and Paging with just one line of code using jQuery DataTables as these features are a must have for all tables and grids.

Brief Note

To have Sorting, Searching, and Paging for a table, it takes lot of efforts to write code to have all these features. But jQuery Datatable is here to rescue you.

jQuery DataTables support both client side processing and as well as server side processing. Here, I will discuss client side data processing. For details regarding server side, refer to www.datatables.net.

When to Use Server Side and Client Side ??

If you are well aware that your record count will not exceed 10,000 records, then go for client side, else choose server side.

Let's Start

jQuery Datatables work on plain HTML tables, so it doesn't matter what server side technology you use. Either you use .NET or Java or PHP or whatever it may be.
Let's assume you have a plain HTML table as below. I am using ASP.NET MVC razor view for this tip. Below is a plain HTML table of razor view. Don't get confused with the Class names I have used here. You can leave the Class attribute blank .

HTML
<table id="table_id" 
class="table table-condensed table-striped table-hover">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Descriptions)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Product)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Employee.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EstEndDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EstHours)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Status)
            </th>
            <th></th>
        </tr>
    </thead>

    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Descriptions)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CategoryMaster.Title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Employee.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EstEndDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EstHours)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Status)
                </td>
                <td>
                   @Html.ActionLink(Resources.Edit, "Edit", 
            new { id = item.ID }, htmlAttributes: new {                     
                @class = "btn btn-default btn-sm" })
                </td>
            </tr>
        }
    </tbody>
</table>

And its output is as follows, as you can see an HTML table without any features like Paging, Sorting, Searching, etc.

Image 1

Now let's apply the DataTables to our plain HTML table and see the reaction of that.

Note: In order for jQuery DataTable to work, three components are important:

  • Table ID
  • <thead>
  • <tbody>

You must specify these three in your HTML table.

Below is the code for using data table. This tip assumes you know the basics of jQuery. I have applied the Datatable on the above HTML table using its ID "table_id" .

HTML
<script type="text/javascript">
    $(document).ready(function () {
        $('#table_id').dataTable();
    });
</script>

And reference the following JS and CSS so that our DataTable can act:

HTML
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
// JQuery Reference, If you have added jQuery reference in your master page then ignore, 
// else include this too with the below reference

<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">

Now save your application, and hit the button to RUN and see DataTables in Action.

Image 2

Our Plain HTML table turned in to a fantastic table with all features Sorting, Filtering, Paging.

Ok. I know what you are thinking. You are thinking that the table style is very simple. So come on, let's have a good style of your choice .You may be thinking how to style the table with CSS and jQuery. Not needed. Just Remove the old CSS and JS references which you added earlier and replace with this one.

HTML
<script 
src="https://code.jquery.com/jquery-1.11.1.min.js"></script> // JQuery Reference

<script 
src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script 
src="https://cdn.datatables.net/plug-ins/9dcbecd42ad/integration/jqueryui/dataTables.jqueryui.js">
</script>
<link rel="stylesheet" 
href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" 
href="https://cdn.datatables.net/plug-ins/9dcbecd42ad/integration/jqueryui/dataTables.jqueryui.css">

Now let's run our app and see the result:

Image 3

Looks fine. Isn't it ?? We have styled our Datatable perfectly. No efforts we have taken so far. I mean just minimum efforts. We have not written any server side code, no jQuery or JavaScript code. Nothing, just with few steps, we have got awesome results.

Still not satisfied with the theme ??

HTML
http://jqueryui.com/themeroller/

Follow the above link, select "Gallery" Tab and choose the theme you like, just note down the name of the theme and replace the name here.

HTML
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/
smoothness/jquery-ui.css">

You have already added the above link. Just change the name. Here, the theme name is "Smoothness". Replace this with your theme name. Your selected theme will be applied, and you can see the new theme in action.

Till now, what I have discussed is just the basics of DataTable. To customize the table more, we need to pass some parameters. Here, I will discuss some examples on customizing the table.

  • In the paging section, you can see only Previous and Next buttons are displaying, now we customize our table to display First Previous Next Last buttons, just pass a parameter as below.
    HTML
    <script type="text/javascript">
        $(document).ready(function () {
            $('#table_id').dataTable({
               "pagingType": "full_numbers",
             });
        });
    </script>

    Hope you got the result !!!

  • By default, the number of records per page is displaying 10 ,25 ,50 ,100 in drop down List . We can customize it according to our needs. An example is shown below:
    HTML
    <script type="text/javascript">
        $(document).ready(function () {
            $('#table_id').dataTable({
               "pagingType": "full_numbers",
               "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
             });
        });
    </script>
  • If you select 100 records per page, the table grows longer, isn't it. So we need a fixed sized table so that even if we choose 1000 records per page, the size of the table will remain constant, a vertical scroll bar will appear in the table to scroll down the records.
    HTML
    <script type="text/javascript">
        $(document).ready(function () {
            $('#table_id').dataTable({
               "pagingType": "full_numbers",
               "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
               "scrollY"  : "400px"
             });
        });
    </script>
  • Ok. If you don't need some features like searching or sorting or paging. You can disable them too by passing specific parameters.
    HTML
    <script type="text/javascript">
        $(document).ready(function () {
            $('#table_id').dataTable({
              "paging" : false,
              "ordering" : false,
              "info"  : false,
              "searching" : false 
            }); 
        }); 
    </script>

Still need more and more and more features and customization, refer to the below site:

  • http://www.datatables.net/

Interested to know your feedback or any mistakes I have made, since this is my first post on CodeProject.

Points of Interest

DataTables is a plug-in for the jQuery JavaScript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

History

  • 21st November, 2014: Initial version

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSource code Pin
tdt2320-Dec-18 2:19
tdt2320-Dec-18 2:19 
Do you have the source code for this project that I can use?
AnswerRe: Source code Pin
alahari8030-Dec-19 10:45
alahari8030-Dec-19 10:45 
GeneralRe: Source code Pin
tdt2331-Dec-19 2:00
tdt2331-Dec-19 2:00 
Questioncan you please add detailed information where to add codes etc. Pin
DR. Patel16-May-18 3:12
DR. Patel16-May-18 3:12 
Questionpaging issue Pin
Yogi S.25-Feb-17 8:29
Yogi S.25-Feb-17 8:29 
AnswerRe: paging issue Pin
Mohammed Sadullah6-Apr-18 2:55
Mohammed Sadullah6-Apr-18 2:55 
Generaldatatable Pin
Member 127710151-Oct-16 19:11
Member 127710151-Oct-16 19:11 
GeneralRe: datatable Pin
Mohammed Sadullah6-Apr-18 2:42
Mohammed Sadullah6-Apr-18 2:42 
QuestionRazor page Pin
Member 116474397-Jun-15 18:43
Member 116474397-Jun-15 18:43 

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.