Search code examples
javascriptrazorcheckboxdatatablesasp.net-core-mvc

How can I adapt the following datatable script code which uses checkbox all to my asp.net core app?


Recently, I installed the Datatable library in my Asp.net app, and is very useful!

I wanted one of my Datatables to have a "Checkbox all" that when pressed, would mark all the existing checkboxes in the current rows of the table which are filtered, and aslo I wanted that all of those checkboxes were part of a group with a name attribute assigned. And when searching, I found a already-made Script that does just what I want!

This one: https://jsfiddle.net/gyrocode/abhbs4x8/

but I'm having a hard time trying to understand how the heck I should adapt this script to my app environment. Since I use a Model instead of ajax/json?, and unlike the link code, I want to put a checkbox manually in each td row of my table, instead of making them appear in an empty "td", as the link code does (thing I don't understand exactly how the code does it).

Can someone help me adapt the code made by gyrocode too my app? Thank you very much in advance.

My view code without gyrocode's jquery datable script:

@model IEnumerable<Co.Models.Com>

<div class="container">
    <div class="card level-3">
        <h3>List</h3>

        <link rel="stylesheet" type="text/css" href="~/DataTables/datatables.min.css" />

        <div>
            <table class="table table-sm table-bordered select" id="tabla">
                <thead class="thead-dark">
                    <tr>
                        <th><input name="select_all" value="1" type="checkbox"></th>
                        <th>
                            <div>Nomb</div>
                        </th>
                        <th>
                            <div>Fech</div>
                        </th>
                        <th>
                            <div>AAA</div>
                        </th>
                        <th>
                            <div>Tuuu</div>
                        </th>
                        <th>
                            <div>Hor</div>
                        </th>
                        <th>
                            <div>Mino</div>
                        </th>
                        <th><div></div></th>
                        <th>
                        </th>
                        <th><div></div></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                    <tr>
                        <td><input name="group" [email protected] type="checkbox">
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Nom)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Fech)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Aombr)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Tip)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Hor)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Tooo)
                        </td>
                        <td>
                            <a class="btn btn-sm btn-primary" asp-action="Edit" asp-route-id="@item.Id">
                                EDIT
                            </a>
                        </td>
                        <td>
                            <a class="btn btn-sm btn-primary" asp-action="Details" asp-route-id="@item.Id">
                                DETAILS
                            </a>
                        </td>
                        <td>
                            <a class="btn btn-sm btn-danger" asp-action="Delete" asp-route-id="@item.Id">
                                DELETE
                            </a>
                        </td>
                    </tr>
                    }
                </tbody>
            </table>
        </div>

<script src="~/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="~/DataTables/datatables.min.js"></script>
<script>
    $("#tabla").dataTable({

        responsive: true,

        buttons: [
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ],
    });
</scrip>

Jquery Datatable: https://datatables.net/download/

(PD: yes, I tried to just change my table Id from "tabla" to "example", but that wasn't enough to make the code work)


Solution

  • For how to apply gyrocode's code to your code,you could check the following code.And be sure change $("#tabla").dataTable({}) to $("#tabla").DataTable({}):

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
    <script>          
    function updateDataTableSelectAllCtrl(table) {
        var $table = table.table().node();
        var $chkbox_all = $('tbody input[type="checkbox"]', $table);
        var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
        var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
    
        // If none of the checkboxes are checked
        if ($chkbox_checked.length === 0) {
            chkbox_select_all.checked = false;
            if ('indeterminate' in chkbox_select_all) {
                chkbox_select_all.indeterminate = false;
            }
    
            // If all of the checkboxes are checked
        } else if ($chkbox_checked.length === $chkbox_all.length) {
            chkbox_select_all.checked = true;
            if ('indeterminate' in chkbox_select_all) {
                chkbox_select_all.indeterminate = false;
            }
    
            // If some of the checkboxes are checked
        } else {
            chkbox_select_all.checked = true;
            if ('indeterminate' in chkbox_select_all) {
                chkbox_select_all.indeterminate = true;
            }
        }
    }
    
    $(document).ready(function () {
        // Array holding selected row IDs
        var rows_selected = [];
        var table = $("#tabla").DataTable({
    
            responsive: true,
    
            buttons: [
                'excelHtml5',
                'csvHtml5',
                'pdfHtml5'
            ],
        });
    
        // Handle click on checkbox
        $('#tabla tbody').on('click', 'input[type="checkbox"]', function (e) {
            var $row = $(this).closest('tr');
    
            // Get row data
            var data = table.row($row).data();
    
            // Get row ID
            var rowId = data[0];
    
            // Determine whether row ID is in the list of selected row IDs 
            var index = $.inArray(rowId, rows_selected);
    
            // If checkbox is checked and row ID is not in list of selected row IDs
            if (this.checked && index === -1) {
                rows_selected.push(rowId);
    
                // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
            } else if (!this.checked && index !== -1) {
                rows_selected.splice(index, 1);
            }
    
            if (this.checked) {
                $row.addClass('selected');
            } else {
                $row.removeClass('selected');
            }
    
            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(table);
    
            // Prevent click event from propagating to parent
            e.stopPropagation();
        });
    
        // Handle click on table cells with checkboxes
        $('#tabla').on('click', 'tbody td, thead th:first-child', function (e) {
            $(this).parent().find('input[type="checkbox"]').trigger('click');
        });
    
        // Handle click on "Select all" control
        $('thead input[name="select_all"]', table.table().container()).on('click', function (e) {
            if (this.checked) {
                $('#tabla tbody input[type="checkbox"]:not(:checked)').trigger('click');
            } else {
                $('#tabla tbody input[type="checkbox"]:checked').trigger('click');
            }
    
            // Prevent click event from propagating to parent
            e.stopPropagation();
        });
    
        // Handle table draw event
        table.on('draw', function () {
            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(table);
        });
    });
    </script>