How do I draw Excel-style data bars in a jQuery DataTable?

戏子无情 提交于 2019-12-04 17:36:47

Should be pretty easy, using fnRowCallback().

I don't have my sample code onhand, but suffice it to say that if you use the example on datatables.net for fnRowCallback, you can use the data value to create a div of an appropriate width. Let me try hacking it together without real-world testing it...

Assume your incoming data (aData) and visible data in the rendered HTML are in the same column (ie. there are no hidden columns). Let's assume further that the column is 4 (from zero origin) and that the value in aData represents a percentage:

"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
  var myValue = aData[4];
  $('td:eq(4)', nRow).html( '<div class="excelBar" style="width:' + myValue + '"></div>' );
  return nRow;
},

That's a super-simplified example. What it does is grab the value found in column 4 of the current row (you could do more logic here to convert; I'm assuming it already comes in as a percentage), modifies the html of column 4 in the rendered HTML to contain a div that is the same width as the value already found. After modifying, it returns the new value of the row (ie. the re-formatted row).

There's a bit more to it... there must already be CSS in place to facilitate this becoming a bar (display: block, etc...), but that's the long and the short of it.

What about trying to use the fnRender method like this, but instead add a styled div like this:

fnRender: function (object) {
    return "<div style=width: "+obj.data[0]+"%; />"
}

Can't comment so new answer. I had to make a small change to accepted answer and add in 'px' to the div width:

"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
  var myValue = aData[4];
  $('td:eq(4)', nRow).html( '<div class="excelBar" style="width:' + myValue + 'px"></div>' );
  return nRow;
},

Databar works out of the box:

$("table").dataTable({}, $("table").databar());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!