jQuery DataTables:隐藏最后一行的“删除"按钮 [英] jQuery DataTables: hide 'delete' button for the last row

查看:18
本文介绍了jQuery DataTables:隐藏最后一行的“删除"按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable,它在某些情况下可以返回多个页面.返回的每一行,显示一个删除按钮,但我需要它来隐藏返回的最后一行的这个按钮,无论是 1 pg 还是多个,所以 css 不能在此使用.

I have a DataTable which can return multiple pages in some cases. Each row returned, displays a delete button but what i need it to hide this button on the very last row returned, whether 1 pg or multiple so css cant be used in this.

我不知道如何实现这个,因为 DataTables 对我来说是新的

I have no idea how to implement this as DataTables are new to me

以下是我当前的代码,除了隐藏按钮外,其他工作正常,希望你能告诉我如何实现这一点

Below is my current code i have which is working fine except for the hiding of the button, hope you can and show my how to implement this

// Existing rule datatable creator
var existingRuleTable = $('#existingRulesDataTable')
.on( 'error.dt', function () {
    $('#todrexitingrules').hide();
    $('#errorModal').modal('show');
    $('#errorModal').on('shown.bs.modal', function () {
        $('#errorModalCloseButton').focus();
    })
    $('#existingRuleError').html(
                    '<p>There was an issue retrieving the data. Please try again.</p>'
                +   '<p>If the error keeps occurring, please get in touch.</p>');
})
.DataTable({
    "ordering": false,                                                  // Allows ordering
    "searching": false,                                                 // Searchbox
    "paging": true,                                                     // Pagination
    "info": false,                                                      // Shows 'Showing X of X' information
    "pagingType": 'simple_numbers',                                     // Shows Previous, page numbers & next buttons only
    "pageLength": 10,                                                   // Defaults number of rows to display in table. If changing this value change the show/hide below
    "dom": '<"top"f>rt<"bottom"lp><"clear">',                           // Positions table elements
    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],              // Sets up the amount of records to display
    "fnDrawCallback": function () {
        if ($('#existingRulesDataTable').DataTable().rows().count() < 11) {
            $("div[class='bottom']").hide();                            // Hides paginator & dropdown if less than 11 records returned
        } else {
            $("div[class='bottom']").show();                            // Shows paginator & dropdown if 11 or more records are returned
        }
    },
    'ajax': {
        "type": 'GET',
        "url": "js/dataTable.json",                                     // TODO > Needs to be changed when actual file resolved
        "data": function (data) {
            return data;
        },
        "dataSrc": function(res){
            existingRuleTableCount = res.data.length;
            return res.data;
        }
    },
    "columns": [                                                        // Display JSON data in table
        { "data": "position" },
        { "data": "startTime" },
        { "data": "endTime" },
        { "data": "selectedDays" },
        { "data": "selectedDates" },
        { "data": "selectedMonths" },
        { "data": "timeRange" },
        {
            "data": null,
            "render": function (data) {
                if (buttonclicked == 'Modify') {                        // Displays the radio button when 'Mod' clicked
                    return  '<label class="c-radio" style="margin-bottom: 0px">'
                        +   '<input type="radio" name="existingRuleActionRadioButton" value="option1">'
                        +       '<span class="fa fa-check"></span>'
                        +   '</label>';
                } else if (buttonclicked == 'Delete') {                 // Displays the delete button when 'Del' clicked
                    return '<button name="deleteRuleButton" class="btn btn-danger" id="' + data.position + '">'
                        + '<i class="fa fa-trash-o" style="font-size: large"></i>'
                        + '</button>';
                } else {
                    return ''; // Needed for the 'Add' button click
                }
            }
        },
    ],
    "createdRow": function (row, data, dataIndex) {
        if (data.startTime == 'Anytime') {
            $('td:eq(1)', row).attr('colspan', 2).css('text-align', 'center').html('All day');  // Adds COLSPAN attribute, centers the wording and changes it from 'Anytime'
            $('td:eq(2)', row).css('display', 'none');                                          // Hides cell next to the cell with COLSPAN attribute
        }

        if (data.timeRange == '-w') {
            $('td:eq(6)', row).html('Working hours');          // Changes text returned by JSON if '-w'
        } else if (data.timeRange == '-oo') {
            $('td:eq(6)', row).html('Out of office hours');    // Changes text returned by JSON if '-oo'
        }
    },
    "destroy": true,
});

我已经尝试了以下但不太确定在哪里添加它,因为我说我是新手并且仍在学习 DataTables 所以我尝试将它添加到 createdRow> 部分,但它不起作用

I have tried the below but not too sure where to add it, as i said i'm new and still learning about DataTables so i tried adding this to the createdRow section but it didn't work

$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) {
    return {
        "iStart":         oSettings._iDisplayStart,
        "iEnd":           oSettings.fnDisplayEnd(),
        "iLength":        oSettings._iDisplayLength,
        "iTotal":         oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
        "iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
    };
}

$.extend(true, $.fn.dataTable.defaults, {
    "fncheckPage": function() {
        var Page = this.fnPagingInfo().iPage;
        if ((+Page + +1) == this.fnPagingInfo().iTotalPages)
        $('#existingRulesDataTable tr:last').find("[name='deleteRuleButton']").hide();
    }
});

无论数据返回 1 条记录还是 100 条记录,我都需要删除最后一个 button.下面的屏幕显示有 2pg,我需要将 button 隐藏在 pg 2 的最后一个 row 上,但在最后一个 row 上显示第一页因此为什么 css 不适合我

Whether the data returns 1 or 100 records, i need the last button to be removed. The screen below shows that there are 2pg's which i need the button hiding on pg 2 in the last row BUT displayed for the last row on the first page hence why css wont wont for me

推荐答案

我可以建议不要隐藏删除"按钮,当您获得表格中的最后一个条目时(从用户的角度来看,这看起来很尴尬),而是禁用它?

May I recommend not to hide 'delete' button, when you got the last entry in your table (which will look awkward, from user standpoint), but rather to disable that?

这是我的观点的例子(我相信,你会理解这个想法):

Here's the example of my point (I'm sure, you'll grasp the idea):

//table data
const srcData = [
  {name: 'apple', category: 'fruit'},
  {name: 'banana', category: 'fruit'},
  {name: 'carrot', category: 'vegie'},
  {name: 'pineapple', category: 'fruit'},
  {name: 'kiwi', category: 'fruit'},
];
//table initialization
const dataTable = $('#mytable').DataTable({
  sDom: 'tp',
  data: srcData,
  ordering: false,
  pageLength:3,
  drawCallback: () => {
    const table = $('#mytable').DataTable();
    $(table.row(table.rows(':last')).node()).find('button').remove();
  },
  columns: [
    {title: 'Name', data: 'name'},
    {
      title: 'Category', 
      data: 'category', 
      render: data => data+'<button class="del">x</button>'},
  ]
});
//'delete' button callback
$('#mytable').on('click', 'td button', function(){
  dataTable.row($(this).closest('tr')).remove().draw();
});

tbody td button {float:right}

<!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="mytable"></table>
</body>
</html>

这篇关于jQuery DataTables:隐藏最后一行的“删除"按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆