简体   繁体   中英

How to add an index column to a dataTables table?

I have a table which is populated using jQuery dataTables. I want to know:

  1. How to add an index column. The dataTables.net site has an example which tells how to give a present index file the index properties not how to make it.

  2. I want to make one of my columns a volume slider. It has only a number which is between 0-100 and want to use jQueryUI slider to make it. Where should I intialise the slider function? Before or inside of dataTables initialization function or after it, and how?

Adding an index column is covered pretty well in the online documentation here: https://datatables.net/examples/api/counter_columns.html

As for the volume slider, I did find a hack-y way to get it working. I added an empty th in the thead and a td at the beginning of each row in the tbody. The first td has the slider div and a rowspan of 3 (my example has only 3 rows). The other tds are empty with a style of display:none.

<table id="myTable" class="display">
    <thead>
        <tr>
            <th></th>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td rowspan="3">
                <div id="slider"></div>
            </td>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
        </tr>
        <!-- Other rows here -->
    </tbody>
</table>

In the JS, I used the example shown in the documentation for an index column, with several changes. I am initializing the slider on "initComplete" of the DataTable, and again when the table is sorted or searched.

var table = $("#myTable").DataTable({
    //Table options here
    "initComplete":function(){
        $("#slider").slider(sliderOpts);
    }
});

table.on('order.dt search.dt', function(){
    table.column(0, {search:'applied', order:'applied'}).nodes().each(function(cell, i){
        if(i == 0){
            $(cell).attr("rowspan","3").html("<div id='slider'></div>").css("display","table-cell");
            $("#slider").slider(sliderOpts);
        } else {
            cell.innerHTML = '';
            $(cell).css("display","none")
        }
    })
}).draw();

Here is a jsfiddle of my solution: https://jsfiddle.net/r7jwv76L/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM