EzDevInfo.com

datatables interview questions

Top datatables frequently asked interview questions

DataTables fixed headers misaligned with columns in wide tables

Problem

When using the sScrollX, sScrollXInner and/or sScrollY to achieve a fixed header table with its inner content scrolling, the headers of the table go out of alignment with the rest of the body in Chrome and IE. Firefox on the other hand displays them perfectly.

Using the version 1.9.4, as far as I can tell, this issue only occurs when there is a lot of data with fluctuating widths, and with words that are very long/unwrappable combined in the same columns as small ones. Also the table in question needs to be fairly wide.

All these factors are demonstrated in this fiddle: http://jsfiddle.net/pratik136/etL73/12/embedded/result/

Output

Chrome:
Chrome Screenshot

IE:
IE9 Screenshot

Firefox
Firefox Screenshot

Suggested Solutions

These solutions have been suggested before but have had no effect on my implementation. Owing to some of these suggestions, I setup a clean plain vanilla demo as I wanted to ensure that no other code was contributing to this effect.

  • turn-off/remove all my css
  • setTimeout( function () { oTable.fnAdjustColumnSizing(); }, 10 );
  • calling oTable.fnFilter( "x",0 ) and oTable.fnFilter( "",0 ) in that order
  • "sScrollXInner": "100%"
  • get rid of all widths

The only solution that I found to the misaligned headers was taking out sScrollX and sScrollY, but this can't be counted as a solution as you lose the fixed header/inner content scrolling functionality. So sadly it's a temporary hack, not a fix!

Note

To edit/play with the latest fiddle: http://jsfiddle.net/pratik136/etL73/12

I have tried various combinations which can be observed in the revision history of the fiddle by using the link http://jsfiddle.net/pratik136/etL73/#REV# where 1 <= #REV# <=12

History

StackO
This question has been asked before: jQuery Datatables Header Misaligned With Vertical Scrolling
but the vital difference is that the OP of that question mentioned that they were able to fix the issue if all CSS was removed, which is untrue in my case, and I have tried a few permutations, thus thought the question worthy of a repost.

External
This issue has also been flagged on the DataTables forum:

This issue has driven me nuts! Please contribute your thoughts!


Source: (StackOverflow)

jquery datatables hide column

Is there a way with the jquery datatables plugin to hide (and show) a table column?

I figured out how to reload the table data: using fnClearTable and fnAddData.

But my issue is that in one of my views for the table (e.g. a hidden mode) I don't want to show certain columns.


Source: (StackOverflow)

Advertisements

How to show empty data message in Datatables

Suppose i get empty data from server sometimes, i want to display No Data found message in DataTables?. How is this possible?


Source: (StackOverflow)

Disable sorting on last column when using jQuery DataTables

I'm using jQuery DataTables in a project and I would like to know how to disable sorting for the last column. I want to implement this site-wide.

Right now I have the following code:

<!-- jQuery DataTable -->
    <script src="../assets/js/plugins/dataTables/jquery.datatables.min.js"></script>
    <script>
        /* Default class modification */
        $.extend( $.fn.dataTableExt.oStdClasses, {
            "sWrapper": "dataTables_wrapper form-inline"
        } );

        /* API method to get paging information */
        $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
        {
            return {
                "iStart":         oSettings._iDisplayStart,
                "iEnd":           oSettings.fnDisplayEnd(),
                "iLength":        oSettings._iDisplayLength,
                "iTotal":         oSettings.fnRecordsTotal(),
                "iFilteredTotal": oSettings.fnRecordsDisplay(),
                "iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
                "iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
            };
        }

        /* Bootstrap style pagination control */
        $.extend( $.fn.dataTableExt.oPagination, {
            "bootstrap": {
                "fnInit": function( oSettings, nPaging, fnDraw ) {
                    var oLang = oSettings.oLanguage.oPaginate;
                    var fnClickHandler = function ( e ) {
                        e.preventDefault();
                        if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                            fnDraw( oSettings );
                        }
                    };

                    $(nPaging).addClass('pagination').append(
                        '<ul>'+
                            '<li class="prev disabled"><a rel='nofollow' href="#">&larr; '+oLang.sPrevious+'</a></li>'+
                            '<li class="next disabled"><a rel='nofollow' href="#">'+oLang.sNext+' &rarr; </a></li>'+
                        '</ul>'
                    );
                    var els = $('a', nPaging);
                    $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
                    $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
                },

                "fnUpdate": function ( oSettings, fnDraw ) {
                    var iListLength = 5;
                    var oPaging = oSettings.oInstance.fnPagingInfo();
                    var an = oSettings.aanFeatures.p;
                    var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

                    if ( oPaging.iTotalPages < iListLength) {
                        iStart = 1;
                        iEnd = oPaging.iTotalPages;
                    }
                    else if ( oPaging.iPage <= iHalf ) {
                        iStart = 1;
                        iEnd = iListLength;
                    } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                        iStart = oPaging.iTotalPages - iListLength + 1;
                        iEnd = oPaging.iTotalPages;
                    } else {
                        iStart = oPaging.iPage - iHalf + 1;
                        iEnd = iStart + iListLength - 1;
                    }

                    for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
                        // Remove the middle elements
                        $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                        // Add the new list items and their event handlers
                        for ( j=iStart ; j<=iEnd ; j++ ) {
                            sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                            $('<li '+sClass+'><a rel='nofollow' href="#">'+j+'</a></li>')
                                .insertBefore( $('li:last', an[i])[0] )
                                .bind('click', function (e) {
                                    e.preventDefault();
                                    oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                                    fnDraw( oSettings );
                                } );
                        }

                        // Add / remove disabled classes from the static elements
                        if ( oPaging.iPage === 0 ) {
                            $('li:first', an[i]).addClass('disabled');
                        } else {
                            $('li:first', an[i]).removeClass('disabled');
                        }

                        if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                            $('li:last', an[i]).addClass('disabled');
                        } else {
                            $('li:last', an[i]).removeClass('disabled');
                        }
                    }
                }
            }
        });

        /* Show/hide table column */
        function dtShowHideCol( iCol ) {
            var oTable = $('#example-2').dataTable();
            var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
            oTable.fnSetColumnVis( iCol, bVis ? false : true );
        };

        /* Table #example */
        $(document).ready(function() {
            $('.datatable').dataTable( {
                "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sLengthMenu": "_MENU_ records per page"
                }
            });
            $('.datatable-controls').on('click','li input',function(){
                dtShowHideCol( $(this).val() );
            })
        });
    </script>

Source: (StackOverflow)

How can I remove the search bar and footer added by the jQuery DataTables plugin?

I am using jQuery DataTables.

I want to remove the search bar and footer (showing how many rows there are visible) that is added to the table by default. I just want to use this plugin for sorting, basically. Can this be done?


Source: (StackOverflow)

disable a column sorting using jquery datatables

I am using the jQuery datatables plugin to sort the table fields. My question is how do I disable sorting for a particular column? I have tried with the following code, but it did not work:

"aoColumns": [
    { "bSearchable": false },
    null
]   

I have also tried the following code:

"aoColumnDefs": [
     { "bSearchable": false, "aTargets": [ 1 ] }
 ]

but this still did not produce the desired results.


Source: (StackOverflow)

jquery datatables default sort

I am trying to set the default sort to the second column in my jquery datatable. It by default sorts by index 0. I am using the "aaSorting": [[ 1, "asc" ]] syntax but it highlights the column which I don't want on initial load. How can I set the default sort of a specific column without it highlighting the column as if no sorting was involved and the 0 index column was being used.


Source: (StackOverflow)

Datatables - Search Box outside datatable

I'm using DataTables (datatables.net) and I would like my search box to be outside of the table (for example in my header div).

Is this possible ?


Source: (StackOverflow)

Using Jquery Datatable with AngularJs

I'm trying to use the jquery datatable plugin in my angularjs project. but my question is does it support lazy loading of value for angularjs? i want beacuse i have many row. how to use datatable pipeline with angularjs.

There is a solution for pagination in here. How to use the solution with angularjs?


Source: (StackOverflow)

how to remove pagination in datatable

I am new in jQuery. I have used Datatables in grid but need not pagination.

There is a list of orders in one page and I show them in a Datatable grid but in bottom I do not want to show pagination. Is there any way to remove or hide pagination from the data table by using a bit customization on the jQuery library.

enter image description here

I have tried to customize it but I found very few methods for do it..

Thanks in advance.


Source: (StackOverflow)

How to delete current row with jquery datatable plugin

I have a column with buttons in a table I'm using jQuery datatable plugin. The buttons say "Remove" and the idea is that when you click on that button it deletes the current row in the table.

When I call fnDeleteRow it seems to work the first time but no any further time for that row so it looks like its not really deleting the row properly.


Source: (StackOverflow)

dataTable() vs. DataTable() - why is there a difference and how do I make them work together?

The vast majority of the documentation for this plugin indicates that you initialize it with

$('#example').dataTable();

However http://www.datatables.net/examples/api/multi_filter_select.html initializes using

$('#example').DataTable();

The resultant objects differ quite a lot, and the example URL above doesn't work when I initialize with a lower-case 'D', however pretty much everything else requires the lower-case 'D' initialization.

Can someone please explain to me why there's a difference, and how to make the two play nice together? Essentially I need the multi-filter-select functionality, but also need to tack on some other calls / plugins, which don't seem to like the upper-case 'D' initialization.


Source: (StackOverflow)

Correctly Suppressing Warnings in DataTables?

I'm trying to correctly suppress warnings (alerts) in DataTables. The standard behavior of DataTables is to throw a javascript alert when an error occurs; however, this is currently inconvenient for me. I have been trying to convert the warning to a javascript error by

$.fn.dataTableExt.sErrMode = 'throw';

Which works correctly, but this stops the current javascript execution, which is not what I want. So, I wrapped the DataTables operations (init and changes) in a try-catch with no error handling; however, this also halts the javascript execution. (Tested on Chrome and Firefox)

My question is how do I go about getting rid of these errors/alerts for the purposes of debugging? I'm trying to debug other parts of my script, but these alerts keep on getting in the way.


Source: (StackOverflow)

disable pagination if there is only one page in datatables

I am implementing datatbales and according to my requirement, most of the things have been resolved except the pagination issue. In my case for every time pagination navigation is displaying. I want to disable the pagination navigation if there is only one page at all.How to do that? My code is like:

JS

<script>
  function fnFilterColumn(i) {

    $('#example').dataTable().fnFilter(
      $("#col" + (i + 1) + "_filter").val(),
      i
    );
  }
  $(document).ready(function() {


    $('#example').dataTable({
      "bProcessing": true,
      "sAjaxSource": "datatable-interestdb.php",
      "bJQueryUI": true,
      "sPaginationType": "full_numbers",
      "sDom": 'T<"clear">lfrtip',
      "oTableTools": {
        "aButtons": [

          {
            "sExtends": "csv",
            "sButtonText": "Save to CSV"
          }
        ]
      },
      "oLanguage": {
        "sSearch": "Search all columns:"
      }


    });


    $("#example").dataTable().columnFilter({
      aoColumns: [
        null,
        null,
        null,
        null
      ]
    });


    $("#col1_filter").keyup(function() {
      fnFilterColumn(0);
    });

  });
</script>

HTML

<table cellpadding="3" cellspacing="0" border="0" class="display userTable" aria-describedby="example_info">

  <tbody>
    <tr id="filter_col1">
      <td>Interest:</td>
      <td>
        <input type="text" name="col1_filter" id="col1_filter">
      </td>
    </tr>
  </tbody>
</table>


<table width="100%" border="0" align="center" cellpadding="2" cellspacing="1" class="form_table display" id="example">

  <thead>
    <tr>
      <th class="sorting_asc" width="25%">Interest</th>
      <th width="25%">Name</th>
      <th width="25%">Email</th>
      <th width="25%">Contact No</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td colspan="4" class="dataTables_empty">Loading data from server</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </tfoot>


</table>

Source: (StackOverflow)

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

Does anybody please know, what is wrong with the very simple HTML file below?

enter image description here

I am just trying to use an array of objects as the data source for DataTables:

tests.html:

<html>
<head>
<link type="text/css" rel="stylesheet" rel='nofollow' href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<link type="text/css" rel="stylesheet" rel='nofollow' href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.2/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.2/jquery.dataTables.min.js"></script>
<script type="text/javascript">

var data = [
    {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]},
    {"Name":"NRB Boot","Result":"PASS","ExecutionTime":"00:00:50.5000000","Measurement":[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]},
    {"Name":"NvMgrCommit","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]},
    {"Name":"SyncNvToEFS","Result":"PASS","ExecutionTime":"00:00:01.2500000","Measurement":[]}
];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name' },
                        { mData: 'Result' },
                        { mData: 'ExecutionTime' }
                ]
        });
});

</script>
</head>
<body>

<table id="tests">
<thead>
<tr>
<th>Name</th>
<th>Result</th>
<th>ExecutionTime</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

</body>
</html>

UPDATE: Ok, I've got the answer from the author to use a newer version of DataTables or rename mData to mDataProp


Source: (StackOverflow)