Friday, November 9, 2012

jQuery - DataTables Server-side Sorting

I couldn't use the server-side sorting ability of DataTables and needed to implement my own. Here's how I did it:

First - turn off DataTables sorting by setting bSort to false.

2 - Add a hidden Div for the menu for my sorting:

<div id="tabmenu" style="visibility: hidden; display: none; position: absolute; z-index: 6" class="popTableMenu">
 <table cellspacing="0" cellpadding="0">
       <a id="fpopSortDn" href="#" onclick="return inSort('asc')">Sort down</a>
       <a id="fpopSortUp" href="#" onclick="return inSort('desc')">Sort up</a>    

3 - Modify the column heading, adding "onmouseover" and "onclick" events:

<th style="height:26px;" class="heading" onmouseover="inMenuHide()" onclick="inMenuShow(this, '${fieldName}');" ><s:property value="fieldLabel"/></th>

4 - Add the JavaScript to handle the mouse events:

<script type="text/javascript"<
var tSort;

function inSort(direct){
 var mID = $('#${tablename}viewID').val();
 var mAct = $('#${tablename}listActionName').val();
 $('div#divBody').load('/InForm${namespace}/'+mAct+'.action?rpp=' + $('#resPerPage').val() + '&sortBy=' + tSort + '&sortOrder=' + direct + '&viewID=' + mID + '&search=' + $('#${tablename}fastSearch').val());
 return false;

function inMenuShow(cell, field){
 tSort = field;
 var offset = $(cell).offset();
 var cH = $(cell).height();
 var pT = + cH;
 $("#tabmenu").offset({ top: pT, left: offset.left });

function inMenuHide(){
 $("#tabmenu").offset({ top: 0, left: 0 });

Clicking on a column heading will call "inMenuShow" so that the sort memu, the hidden Div, displays below the column:
Clicking on an item in the sort menu wil call the "inSort" method. This method calls my struts action and populates the table container, "divBody", with the returned page. The page that's returned ids the sorted table.

No comments:

Post a Comment

Thank you for commenting!