JM4
JM4

Reputation: 6798

Add URL to jQuery Datatables data set?

I have a jquery datatables which is built dynamically, meaning each row is built using a php mysql database call. Creating the table itself is no problem but there are times I want to add hyperlinks to the data displayed in the set.

For example:

ID   |    Date       |   Amount
----------------------------
1    | April 1, 2011 |  3.95
2    | April 5, 2011 |  4.55
3    | May 9, 2011   |  19.32 

the catch is, the dates above would be a hyperlink and the date format in the URL would be in format of YYYY-mm-dd.

When i do this, datatables wants to treat the entire URL as a data element and thus screws up any sorting I can do on the table after the fact.

Anybody had this issue before? I can't seem to find anything online.

Upvotes: 0

Views: 1485

Answers (3)

Keith.Abramo
Keith.Abramo

Reputation: 6965

You could use fnRender() on that column to return any html you want that column to display.

bUseRendered: true,
fnRender: function(oObj) {
   var id = oObj.aData[0];
   var normalDate = oObj.aData[1];
   var amount = oObj.aData[2];
   var urlDate = oObj.aData[3];
   var isUrlDate = oObj.aData[4];

   if (isUrlDate) {
      return urlDate;
   }
   else {
      return normalDate;
   }
}

Note the

bUseRendered: false

This tells datatables "for this column when sorting use the data passed back NOT the html rendered"

oObj.aData returns the column data from that row. You could return a couple extra HIDDEN columns which contain the data you need to perform that logic. Then your sorting still works and you also have access to the url you need if one exists.

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76890

To sort non standard columns you can define specific functions: here you can find some of them: http://datatables.net/plug-ins/sorting.

in your case you define your own sorting function like this:

jQuery.fn.dataTableExt.oSort['my-date-asc']  = function(a,b) {
    var x = a.match(/date=(.*?)"/)[1].toLowerCase();
    var y = b.match(/title="(.*?)"/)[1].toLowerCase();
        x = x.replace(/-/g, '');
        y = y.replace(/-/g, '');
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['title-string-desc'] = function(a,b) {
    var x = a.match(/date=(.*?)"/)[1].toLowerCase();
    var y = b.match(/date=(.*?)"/)[1].toLowerCase();
        x = x.replace(/-/g, '');
        y = y.replace(/-/g, '');
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

Upvotes: 1

kasdega
kasdega

Reputation: 18786

My guess is that if there is no link this sorts just fine but because there is a link (html) in the column it doesn't work like you'd expect. To me it sounds like it has less to do with the date and more to do with the HTML...

I found this: jquery datatable plugin doesn't seem to sort columns with links properly

Upvotes: 0

Related Questions