Показывать количество строк в табуляторе - PullRequest
0 голосов
/ 14 апреля 2020

В DataTables у нас есть возможность показывать строки 1 из 100. Я хочу сделать то же или подобное в табуляторе. Я использовал этот подход, и он возвращает пустую таблицу:

 var tabulator_table = new Tabulator("#example", {

            columns: [
                { title: "", field: "", headerFilter: "input" },
                { title: "", field: "", headerFilter: "input" },
                { title: "", field: "", headerFilter: "input" },
                { title: "", field: "", headerFilter: "input" },
                { title: "", field: "", headerFilter: "input" },
                { title: "", field: "", headerFilter: "input" },
            ],
            //this part should return row count
            dataFiltered: function (data, field, type, value) {
                //data - the subset of the total table data that has passed the filter and is now 
                     visible
                //field - the field being filtered
                //type - the type of filter being used
                //value - the value of the filter

                //set text in info element to show the number of rows and filters currently applied
                $("#example-table-info").text("rows:" + data.length + " of " + $("#tableID").Tabulator("getData").length +
                    ", filter:" + field + type + value);
            }

        });

В html:

   <div class="footer">
        <p id="example-table-info"></p>
        <div id="myButtons"> Export </div>
    </div>

ошибка: «.tabulator не является функцией»

Я также пытался использовать другой подход:

function myFunction() {
 return $('tr', $(this).find('tbody')).length;
}
 rowctr = $('#tableID').rowCount();
document.getElementById("demo").innerHTML = myFunction();

<p id="demo"></p>

Также я видел на их github, чтобы использовать это:

var activeRowCount = table.getDataCount(true);

Но я не знаю, как и где его применять и вернуть значение в моем теге нижнего колонтитула. Спасибо.

Ответы [ 2 ]

0 голосов
/ 17 апреля 2020

После исследования и помощи вот что я сделал:

var tabulator_table = new Tabulator("#example", {
    columns: [
                    { title: "", field: "", bottomCalc: "count", headerFilter: "input" },
                    { title: "", field: "", bottomCalc: "count", headerFilter: "input" },
                    { title: "", field: "", bottomCalc: "count", headerFilter: "input" },
                    { title: "", field: "", bottomCalc: "count",headerFilter: "input" },
                    { title: "", field: "", bottomCalc: "count", headerFilter: "input" },
                    { title: "", field: "", bottomCalc: "count", headerFilter: "input" },
                ],
    dataFiltered: function(filters, rows) {
                        var el = document.getElementById("search_count");
                        el.innerHTML = rows.length;
                    },
                    dataLoad: function(data) {
                        var el = document.getElementById("total_count");
                        el.innerHTML = data.length;
                    },
      });
      });
             var total_count = $(".tabulator-footer").find('.tabulator-cell:first-child()').text();
            $("#total_count").text(total_count);
   //rest of your js if you have any.

css часть:

   .tabulator-footer {
                display: none;
            }

Html:

 <span style="color:#102D4F;font-size:12px;font-family:Arial, Helvetica, sans-serif">
            Showing <span id="search_count"></span>
            results in total 
            <span id="total_count"></span> 
0 голосов
/ 15 апреля 2020

Вы не должны пытаться манипулировать элементами внутри строк таблицы снаружи. Он использует виртуальный DOM и может сбрасывать эти компоненты без предварительного уведомления.

Кроме того, из-за виртуального DOM вполне вероятно, что большинство элементов, к которым вы обращаетесь, на самом деле не существует, когда вы выполняете запрос. так что вы не сможете считать строки таким образом. Также табулятор не построен с использованием стандартных табличных тегов, поэтому поиск тегов tr не будет работать по этой причине

rownum Formatter

Если вы хотите отобразить номер строки рядом со строкой Проверьте Документация встроенных форматеров и посмотрите на rownum , он позаботится о вещах автоматически:

{title:"Example", field:"example", formatter:"rownum"}

Расчет столбца

В качестве альтернативы вы можете посмотреть, используя Расчет столбца и используя вычисление count , чтобы отобразить эту информацию в строке расчета.

{title:"Example", field:"example", bottomCalc:"count"}

Пользовательский нижний колонтитул

Или вы можете посмотреть Добавление пользовательского элемента в нижний колонтитул , а затем использовать dataFiltered обратный вызов, как указано выше, хотя я бы также использовал обратный вызов dataLoaded , чтобы охватить все базы

//define update function
function updateFooter(data){
   var el = document.getElementByID("row-count");
   el.innerHTML = data.length;
}

var table = new Tabulator("#example-table", {
    columns:[...], //define your columns
    footerElement:"<span id='row-count'></span>", //add element element to footer to contain count
    dataFiltered: updateFooter, //call updateFooter function when callback triggered
    dataLoaded: updateFooter, //call updateFooter function when callback triggered
});

...