Holt59 / datatable

Javascript Plugin for data tables creation
http://holt59.github.io/datatable/
MIT License
108 stars 42 forks source link

Get number of a table row. #36

Open AndreCabrera opened 6 years ago

AndreCabrera commented 6 years ago

Hi,

I have a datatable in my project and i can't display the number of row in the first column of my table; how to get the number (position) of any row?

here's my code:

$('#myTable').datatable({
    data: json,
    identify: 'field1',
    lineFormat: function (id, data) {
    var tr = $('<tr></tr>') ;
    // First <td> element, here display number of row.
        tr.append('<td></td>') ;
        tr.append('<td>'+data['field1']+'</td>') ;
        tr.append('<td>'+data['field2']+'</td>') ;
        tr.append('<td>'+data['field3']+'</td>') ;
        return tr ;
     }
 });

Consider: when delete rows using $('#myTable').datatable('delete', id); or add new rows $('#myTable').datatable('insert', json); the numbers of table rows update automatically, is there a way to do this ?.

thanks.

Holt59 commented 6 years ago

id is the index of the row in the unfiltered dataset, so you could simply use it. Or am I misunderstanding what you want?

AndreCabrera commented 6 years ago

I want to do this:

xsxs

Enumerate all rows automatically, including when filter, add and delete data, is it possible?

Holt59 commented 6 years ago

What do you want to see when you have filtered data? Something like this?

#|    Field1    Field2
1|
3|
4|
6|

If so, you can simply use the id (maybe id + 1).

AndreCabrera commented 6 years ago

nop, let's suppose to I have 6 rows in my datatable in first time, so when I filtered data (for example this filter get me only 3 rows) I want to see : **

| Field1 Field2

1| 2| 3| I don't want this:

| Field1 Field2

1| 4| 6| Another example: if I have 6 rows in first time and I delete the row 5, I want:

| Field1 Field2

1| 2| 3| 4| 5| I don't want:

| Field1 Field2

1| 2| 3| 4| 6| **

Holt59 commented 6 years ago

There is no built-in way, but the row are appended to the tbody element sequentially, so you could simply count the number of tr in the tbody, e.g. (not tested):

lineFormat: function (id, data) {
    var pageRowNum = $(this).find('tbody tr').length;
    var rowNum = (this.getCurrentPage() - 1) * this.options.pageSize + pageRowNum + 1;
    // Whatever you want...
}
AndreCabrera commented 6 years ago

it works !!, thanks so much.