datatables filter with statesave cause issue when

2019-02-27 00:52发布

I have an html page and some javascript code. Below is my working html:

<table class="table table-hover" id="gridHelpDesk">
    <thead>
        <tr>
            <th class="color-white">Employee ID</th>
            <th class="color-white">Name</th>
            <th class="color-white">Email</th>
            <th class="color-white">Survey Status</th>
            <th class="color-white">Start Date</th>
            <th class="color-white">Completed Date</th>
            <th class="color-white">Survey Link</th>
            <th class="color-white">Reactivate Link</th>
            <th class="color-white">Delete Responses</th>
            <th class="color-white">Create New Link</th>
            <th class="color-white">Send Reminder</th>
        </tr>
        <tr>
            <th class="filter">Search Employee ID</th>
            <th class="filter">Search Employee Name</th>
            <th class="filter">Search Employee Email</th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </thead>
</table>

Here is my javascript code:

    var dtGridHelpDesk;
    var EmployeeName;
    var EmployeeID;
    var Email;

    $(document).ready(function () {
        InitializerHelpDeskGRID()
    })

    function InitializerHelpDeskGRID() {

        $('.filter').each(function () {
            var title = $(this).text();
            var classForFilter = $(this).text();
            classForFilter = classForFilter.split(' ').join('');

            $(this).html('<input type="text" class="form-control input-sm ' + classForFilter + '" placeholder="' + title + '" onclick="event.stopPropagation()" onkeypress="event.stopPropagation()" />');

        });

        dtGridHelpDesk = $('#gridHelpDesk').dataTable({
            scrollCollapse: true,
            serverSide: true,
            ajax: {
                url: '@Url.Content("~/Home/GetHelpdeskData")',
                data: SearchHDParams,
                dataSrc: HDGridDataBound,
                type: "POST"
            },
            processing: true,
            processing: "<span class='glyphicon glyphicon-refresh glyphicon-refresh-animate' />",
            bDestroy: true,
            select: true,
            paging: false,
            bLengthChange: false,
            info: false,
            ordering: false,
            searching: true,
            stateSave: true,
            stateLoadParams: function (settings, data) {
                if (data.order) delete data.order;
            },
            columnDefs: [
            {
                targets: 0,
                data: "EmployeeID",

            },
            {
                targets: 1,
                data: "EmployeeName",
            },
            {
                targets: 2,
                data: "Email",
            },
            {
                targets: 3,
                data: "SurveyStatus"
            },
            {
                targets: 4,
                data: "StartedDate"
            },
            {
                targets: 5,
                data: "CompleteDate"
            },
            {
                targets: 6,
                data: "PositionNumber",
                render: function (data, type, full, meta) {
                    return '<button class="btn btn-info btn-sm" onclick="CopyLink(this, \'' + full.SurveyLink + '\')"> Copy </button>'
                }
            },
            {
                targets: 7,
                data: "PositionNumber",
                render: function (data, type, full, meta) {
                    return '<button class="btn btn-success btn-sm" onclick="ReActivateLink(this, \'' + full.PositionNumber + '\')"> ReActivate </button>'
                }
            },
            {
                targets: 8,
                data: "PositionNumber",
                render: function (data, type, full, meta) {
                    return '<button class="btn btn-warning btn-sm" onclick="DeleteResponses(this, \'' + full.PositionNumber + '\')"> Delete & ReActivate </button>'
                }
            },
            {
                targets: 9,
                data: "PositionNumber",
                render: function (data, type, full, meta) {
                    return '<button class="btn btn-default btn-sm" onclick="UpdateLink(this, \'' + full.PositionNumber + '\')"> Create </button>'
                }
            },
            {
                targets: 10,
                data: "PositionNumber",
                render: function (data, type, full, meta) {
                    return '<button class="btn btn-danger btn-sm" onclick="SendReminder(this, \'' + full.PositionNumber + '\')"> Send Reminder </button>'
                }
            }]
        });

        var state = dtGridHelpDesk.api().state.loaded();
        if (state) {
            dtGridHelpDesk.api().columns().eq(0).each(function (colIdx) {
                var colSearch = state.columns[colIdx].search;
                if (colSearch.search) {
                    $('input', dtGridHelpDesk.api().column(colIdx).header()).val(colSearch.search);
                }
            });

            dtGridHelpDesk.api().draw();
        }

        dtGridHelpDesk.api().columns().eq(0).each(function (colIdx) {
            $('input', dtGridHelpDesk.api().column(colIdx).header()).on('keyup change', function () {
                dtGridHelpDesk.api()
                    .column(colIdx)
                    .search(this.value)
                    .draw();
            });
        });
    }

    function SearchHDParams(d) {
        d.EmployeeName = $('.SearchEmployeeName').val()
        d.EmployeeID = $('.SearchEmployeeID').val()
        d.Email = $('.SearchEmployeeEmail').val()
    }

    function HDGridDataBound(response) {
        if (response.IsSuccess == true) {
            return response.gridData;
        }
        else {
            toastr.error("Something went wrong, Please try again after some time.");
        }
    }

The strange thing is that my javascript code fails if I change the order of my Header rows in the html. For example, if I swap the search header with the text in the html, as demonstrated below, then my javascript code fails.

 <table class="table table-hover" id="gridHelpDesk">
    <thead>     
        <tr>
            <th class="filter">Search Employee ID</th>
            <th class="filter">Search Employee Name</th>
            <th class="filter">Search Employee Email</th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>      
        <tr>
            <th class="color-white">Employee ID</th>
            <th class="color-white">Name</th>
            <th class="color-white">Email</th>
            <th class="color-white">Survey Status</th>
            <th class="color-white">Start Date</th>
            <th class="color-white">Completed Date</th>
            <th class="color-white">Survey Link</th>
            <th class="color-white">Reactivate Link</th>
            <th class="color-white">Delete Responses</th>
            <th class="color-white">Create New Link</th>
            <th class="color-white">Send Reminder</th>
        </tr>          
    </thead>
</table>

Why is this happening, and how can I fix it? I do not understand why swapping the order of items in my html would break my javascript like this, nor do I see a clear way to resolve the issue.

I have already tried many possible solutions, but as I am loading data based on my function (SearchHDParams), the javascript over-writes the state. Therefore, none of my solutions so far have worked. Any help is appreciated.

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-27 01:15

CAUSE

Your code dtGridHelpDesk.api().column(colIdx).header() returns th cell from bottom header row which doesn't contain input elements after you switched order of header rows.

SOLUTION 1

The way your code is written, the easiest solution is to use the orderCellsTop option. It will make DataTables return th cell from top header row when you call column().header() API method.

"orderCellsTop": true

It will not cause any problems now because you have ordering disabled. If you decide to enable ordering later, this solution will cause issues because your top row has search boxes and not column headings.

SOLUTION 2

Better solution is to replace code:

$('input', dtGridHelpDesk.api().column(colIdx).header())

with:

$('input', $('th', dtGridHelpDesk.api().table().header()).eq($(dtGridHelpDesk.api().column(colIdx).header()).index()))

This code looks for search boxes in th cells of both header rows, not just bottom one.

查看更多
登录 后发表回答