0
votes

I am using the jQuery DataTables plugin. I don't want my thead columns to line up with the tbody columns, as I am mostly using the header columns as sorting buttons. The header names no longer really fit because I am displaying extra information in the body columns.

I would like the thead columns close together and left aligned at the top of the table. I want the tbody columns to be auto-sized the way DataTables usually works. What is the best way to accomplish this styling?

Also, I feel as though I am abusing DataTables and the table element in general. If you are aware of a cleaner solution to my problem that does not involve rolling my own ajax (for retrieving the table data), sorting, pagination, and filtering, please let me know.

1

1 Answers

1
votes

Remember that in the end, it's a table. the structure of a table is hard to change and the widths of the headers will follow the widths of the body that they encompass.

You say that you are using extra information for sorting? Why not create a container using whatever structure and css you want and then interact with datatables using the api?

You can sort using the api:

$(document).ready(function() {
  var oTable = $('#example').dataTable();

  // Sort immediately with columns 0 and 1
  oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
 } );

For instance, if you'd rather have a button above the table that the user can click instead of the table header themselves, you can do this:

<div id="separateStyledContainer">
    <button id="sortByColumn2">Sort by Column 2</button>
</div>
<table id="datatable">
    <thead>
        <th>Column 1</th>
        <th>Column 2</th>
    </thead>
    <tbody>
        <tr>
            <td>Column 1 Value 1</td>
            <td>Column 2 Value 1</td>
        </tr>
        <tr>
            <td>Column 1 Value 2</td>
            <td>Column 2 Value 2</td>
        </tr>
    </tbody>              
</table>

And here's the JS:

$(function() {

  var table = $("#datatable").dataTable();  

    $("#sortByColumn2").on("click", function() {
      table.fnSort([[1,'asc']]);             
    });        

})​

Here's a working jsFiddle to check out

This way you're not fighting against the table. All of the APIs that datatable makes available are here