How can Checked Child table of Data table

jewel 901 Reputation points
2024-04-10T16:45:00.6566667+00:00

Clicking on a row in my datatable opens a child table. Checked boxes are attached to columns of tables and rows of child tables. I want - when clicking on table column checkbox('className': 'dt-body-center') each row(class="chk_isChecked") of child table under it will be checked. Or if a number is input in any text box (class="txt_qty")of the child table, then all the rows here will be selected(class="chk_isChecked")  and the checked box of the column('className': 'dt-body-center') will also be checked.

Second - If clicking on the checked box of the table column('className': 'dt-body-center') makes the checked box of the child table checked(class="chk_isChecked")  , then if  i click on the table  column("className": 'details-control'), it should not be unchecked.

<style>
td.details-control {
    background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
    cursor: pointer;
}
tr.shown td.details-control {
    background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
}
</style>
<button onclick="addata()" class="btn btn-primary btn-sm">Add </button>
<table id="example" class="display jo" style="width:100%">
haskell
<thead>
    <tr>
        <th ></th>
        <th ></th>
        <th>Order NO</th>
        <th>Total Value</th>
    </tr>
</thead>
</table>
@section Scripts {
@{
    await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script type="text/javascript">
    function format(d) {
        debugger
        var str = '';
        $.each(d.tbl_orderses, function (index, data) {
            str += '<tr>' +
                '<td>' + data.productID + '</td>'+
                '<td>' + data.oredrQty + '</td>' + 
                '<td><input type="number" value="0" class="txt_qty" /></td>' +
                '<td><input type="checkbox" name="Selectone" class="chk_isChecked" id="' + data.productID + '" /></td>' +
                '</tr>'
        });
        return '<table id=ntabl  style="padding-left:50px;">' +
            '<tr>' +
            '<td>ProductID</td><td>oredrQty</td><td>Return Qty</td><td>Check</td>' +
            '</tr>' +
            str +
            '</table>';
    }
    $(document).ready(function () {
        $.ajax({
            url: "/Home/Getrecord",
            type: "Get",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log("succsss" + data);
                var table = $("#example").DataTable({
                    "data": data,
                    "columns": [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        {
                                                           "orderable": false,
                            "data": null,
                            'className': 'dt-body-center',
                            'render': function (data, type, full, meta) {
                                return '<input type="checkbox" class="checkbox_check">';
                            }
                        },
                    
                        { "data": "orderNumber" },
                        { "data": "totalvalue" },
                    ],
                    "order": [[0, 'desc']]
                });
                $('#example tbody').on('click', 'td.details-control', function () {
                    debugger
                    var tr = $(this).closest('tr');
                    var row = table.row(tr);
                    if (row.child.isShown()) {
                        row.child.hide();
                        tr.removeClass('shown');
                    }
                    else {
                        row.child(format(row.data())).show();
                        tr.addClass('shown');
                    }
                });
            },
            error: function (ex) {
                console.log(ex);
            }
                    
        });
       
    });
 
 public JsonResult Getrecord()
  {
  var List = from a in _context.tbl_Orders
             group a by new { a.orderNumber } into g
             select new ordervm
             {
                 orderNumber = g.Key.orderNumber,
                 Totalvalue = g.Sum(x => x.value),
                 tbl_orderses = g.Select(t => new tbl_order
                 {
                     productID = t.productID,
                     oredrQty = t.oredrQty,
                     orderId = t.orderId,
                 }).ToList()
             };
  return Json(List);
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,553 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ping Ni-MSFT 4,335 Reputation points Microsoft Vendor
    2024-04-11T09:18:19.74+00:00

    Hi @jewel,

    For your first requirement, you need check the following code:

    <style>
    td.details-control {
        background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
        cursor: pointer;
    }
    tr.shown td.details-control {
        background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
    }
    </style>
    <button onclick="addata()" class="btn btn-primary btn-sm">Add </button>
    <table id="example" class="display jo" style="width:100%">
    haskell
    <thead>
        <tr>
            <th ></th>
            <th ></th>
            <th>Order NO</th>
            <th>Total Value</th>
        </tr>
    </thead>
    </table>
    @section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
        <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 type="text/javascript">
        function format(d) {        
            var str = '';
            $.each(d.tbl_orderses, function (index, data) {
                str += '<tr>' +
                    '<td>' + data.productID + '</td>'+
                    '<td>' + data.oredrQty + '</td>' + 
                    '<td><input type="number" value="0" class="txt_qty" /></td>' +
                    '<td><input type="checkbox" name="Selectone" class="chk_isChecked" id="' + data.productID + '" /></td>' +
                    '</tr>'
            });
            return '<table id=ntabl  style="padding-left:50px;">' +
                '<tr>' +
                '<td>ProductID</td><td>oredrQty</td><td>Return Qty</td><td>Check</td>' +
                '</tr>' +
                str +
                '</table>';
        }
        $(document).ready(function () {
            $.ajax({
                url: "/Home/Getrecord",
                type: "Get",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log("succsss" + data);
                    var table = $("#example").DataTable({
                        "data": data,
                        "columns": [
                            {
                                "className": 'details-control',
                                "orderable": false,
                                "data": null,
                                "defaultContent": ''
                            },
                            {
                                "orderable": false,
                                "data": null,
                                'className': 'dt-body-center',
                                'render': function (data, type, full, meta) {
                                    return '<input type="checkbox" class="checkbox_check">';
                                }
                            },
                            { "data": "orderNumber" },
                            { "data": "totalvalue" },
                        ],
                        "order": [[0, 'desc']]
                    });
                    $('#example tbody').on('click', 'td.details-control', function () {
                             var tr = $(this).closest('tr');
                                var row = table.row(tr);
                                if (row.child.isShown()) {
                                    row.child.hide();
                                    tr.removeClass('shown');
                                }
                                else {
                                    row.child(format(row.data())).show();
                                    tr.addClass('shown');
                                }
                    });
                        // When clicking on the column checkbox
                        $('#example tbody').on('change', '.checkbox_check', function () {
                            var isChecked = $(this).prop('checked');
                            // Check/uncheck all checkboxes in the child table
                            $(this).closest('tr').next('tr').find('.chk_isChecked').prop('checked', isChecked);
                        });
                        // When inputting a number in any text box
                        $('#example tbody').on('input', '.txt_qty', function () {
                            var quantity = $(this).val();
                            var isChecked = quantity > 0;
                            // Check all checkboxes in the child table
                            $(this).closest('table').find('.chk_isChecked').prop('checked', isChecked);
                            // Check the corresponding column checkbox
                            $(this).closest('table').closest('tr').prev('tr').find('.checkbox_check').prop('checked', isChecked);
                        });                                          
                      
                },
                error: function (ex) {
                    console.log(ex);
                }
            });
              
        })
            </script>
        }
    

    For your second requirement, you need each time send the current table to backend to store the value in the database. Then you can display it in the next time. Otherwise, it will always missing the input value and state. You may consider store it in localStorage which can do in frontend, if you need store multiple value with different key, it can degrade the performance of your web app.
    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.