Search code examples
jquerydatatables

Datatable Delete Row Issue


I have one data table. In that, I insert data on the button click. On each row, one delete button is there. When I Press the Delete button, the row will deleted. But after that, When I add a new row at that time, the deleted row appears again in a data table with new data. I have Uploaded my full code with the Row creation, delete button click all.

// Initialize the array to store unique row IDs
        var uniqueRowIds = [];
 
        // Function to generate a unique row ID
        function generateUniqueId() {
            // Get all existing row IDs
            var existingIds = $('#tblCreateNoteManually tbody tr').map(function () {
                return $(this).attr('data-row-id');
            }).get();
 
            // Generate a unique ID based on the length of the existing list of IDs
            var newId;
            var index = 1;
            do {
                newId = 'row_' + index++;
            } while (existingIds.includes(newId) || uniqueRowIds.includes(newId));
 
            return newId;
        }
 
 
        // Function to append a new row to the table
        function appendRowToDataTable(data) {
            //debugger;
            console.log("In appendRowToDataTable", data);
 
            // Assuming 'tblCreateNoteManually' is the ID of your table
            var tableBody = $('#tblCreateNoteManually tbody');
 
            // Create a new row with a unique ID
            var newRowId = generateUniqueId();
            var newRow = $('<tr>').attr('id', newRowId).attr('data-row-id', newRowId);
 
            // Populate cells in the row using data from the array
            newRow.append('<td>' + (data[0].Product || '') + '</td>');
            newRow.append('<td>' + (data[0].Project || '') + '</td>');
            newRow.append('<td>' + (data[0].WBSElement || '') + '</td>');
            newRow.append('<td>' + (data[0].DRGNo || '') + '</td>');
            newRow.append('<td>' + (data[0].MaterialNo || '') + '</td>');
            newRow.append('<td>' + (data[0].DrgTotalQty || 0) + '</td>');
            newRow.append('<td>' + (data[0].OrderQuantity || 0) + '</td>');
            newRow.append('<td>' + (data[0].UAAuxQTy || 0) + '</td>');
            newRow.append('<td>' + (data[0].AuxBalanceQty || 0) + '</td>');
            newRow.append('<td>' + (data[0].UALogQTy || 0) + '</td>');
            newRow.append('<td>' + (data[0].LogBalanceQty || 0) + '</td>');
            newRow.append('<td><input type="text" class="form-control qty-input" placeholder="Quantity" oninput="validateInput(this)" value="' + (data[0].Qty || '') + '" /></td>');
            newRow.append('<td><input type="text" class="form-control remarks-input" placeholder="Remarks" value="' + ((data[0].Remarks !== null) ? data[0].Remarks : '') + '" /></td>');
            newRow.append('<td><button type="button" class="btn btn-danger btn-sm" onclick="deleteRownew(\'' + newRowId + '\')"><i class="fa fa-close"></i></button></td>');
 
            // Append the new row to the table
            tableBody.append(newRow);
 
            // Add the unique ID to the list
            uniqueRowIds.push(newRowId);
 
            // Show/hide columns or perform any other necessary actions
            showhidecolumn();
        }
 
        // Function to delete a row
        function deleteRownew(rowIdToDelete) {
            // Show the confirmation modal
            $('#confirmationModal').modal('show');
 
            // Set up the event handler for the delete button in the modal
            $('#confirmDeleteBtn').off('click').on('click', function () {
                // Assuming 'tblCreateNoteManually' is the ID of your table
                var tableBody = $('#tblCreateNoteManually tbody');
 
                // Find the row by its unique ID
                var rowToDelete = tableBody.find('tr[data-row-id="' + rowIdToDelete + '"]');
 
                // Remove the row
                rowToDelete.remove();
 
                //// Remove the row ID from the list of unique IDs
                //uniqueRowIds = uniqueRowIds.filter(id => id !== rowIdToDelete);
 
                // Update the uniqueRowIds array to maintain the correct order
                uniqueRowIds = tableBody.find('tr').map(function () {
                    return $(this).attr('data-row-id');
                }).get();
 
                // Reload the table with existing data
                //reloadTable();
 
                // Hide the modal
                $('#confirmationModal').modal('hide');
 
                // Remove the event handler after it's been executed
                $('#confirmDeleteBtn').off('click');
 
            });
        }



[9:15 AM] Vanita Pandya
function GetdatafromDUNo(selectedValue) {

            var Entity = {};

            Entity.DUNo = selectedValue;
 
            $.ajax({

                url: '../HandoverNote/GetDetailfromDUNo/',

                data: JSON.stringify(Entity),

                dataType: "json",

                type: "POST",

                contentType: "application/json",

                success: function (data) {

                    if (data) {

                        console.log("Received data from server:", data);

                        populateTable(data);

                        // Append a new row to the DataTable

                        appendRowToDataTable(data);

                    } else {

                        console.log("No data received from server.");

                    }

                },

                error: function (error) {

                    console.error("Error in AJAX request:", error);

                }

            });

        }
 
        function populateTable(data) {

            if (data && data.length > 0) {

                console.log(data);
 
                if (data.DUNosNotUploaded && data.DUNosNotUploaded !== '') {

                    toastr.error("Error: MaterialNo values not found for JTCDataMaster. MaterialNo(s): " + data.DUNosNotUploaded);

                }
 
                initializeDataTable(data);
 
                if (data.jtcdataListFinal == null) {

                    $("#pUploadStatus").html("No records found in the file.");

                    $("#pUploadStatus").removeClass("hidden").removeClass("bg-danger").addClass("bg-success");

                } else {

                    $("#pUploadStatus").html("File uploaded successfully.");

                    $("#pUploadStatus").removeClass("hidden").removeClass("bg-success").addClass("bg-danger");

                }

            } else {

                console.log("Empty data received from server.");

                // Handle empty data if needed

            }

        }

        $("#next1").click(function () {

            $("#btnaddRow").prop("disabled", true);

            var x = $("#serial").val();

        

            if (!isEmpty(x)) {
 
               

                $("#serial").val("");

                GetdatafromDUNo(x);
 
 
                }

          
        });


<table class="table table-bordered table-striped table-hover headerManually" id="tblCreateNoteManually" width="100%">

                        <thead>

                            <tr>

                                <th class="headManually">Product</th>

                                <th class="headManually">Project</th>

                                <th class="headManually">WBS No</th>

                                <th class="headManually">DRG No</th>

                                <th class="headManually">DU No</th>

                                <th>Total DRG Qty</th>

                                <th>Available Qty with Shop</th>

                                <th>Under Auxilliary Approval</th>

                                <th>Available Qty with Auxilliary</th>

                                <th>Under Logistics Approval</th>

                                <th>Available Qty with Logistics </th>

                                @*@if (ViewBag.UserRole != null)

        {

            if (ViewBag.UserRole == "AuxilliaryUser")

            {

                <th>Available Qty with Logistics </th>

                <th>Qty under Auxilliary Approval</th>

                <th>Qty under Logistics Approval</th>

            }

            else

            {

                <th style="display: none">Available Qty with Logistics </th>

                <th>Qty under Auxilliary Approval</th>

                <th style="display: none">Qty under Logistics Approval</th>

            }

        }*@

                                <th class="qty">Quantity</th>

                                <th>Remarks</th>

                                <th>Action</th>

                            </tr>

                        </thead>

                        @*<tbody>

                                <tr>

                                    <td>

                                        <select class="form-control clearData select2" id="ddlProduct" data-placeholder="Select Product" style="width:100%; ">

                                            <option value="" selected="selected"> Select Product </option>

                                        </select>

                                    </td>

                                    <td>

                                        <select class="form-control clearData select2" id="ddlProject" data-placeholder="Select Project" style="width:100%; ">

                                            <option value="" selected="selected"> Select Project </option>

                                        </select>

                                    </td>

                                    <td>

                                        <select class="form-control clearData select2" id="ddlWBSNo" data-placeholder="Select WBS No" style="width:100%; ">

                                            <option value="" selected="selected"> Select WBS No </option>

                                        </select>

                                    </td>

                                    <td>

                                        <select class="form-control clearData select2" id="ddlDRGNo" data-placeholder="Select DRG No" style="width:100%; ">

                                            <option value="" selected="selected"> Select DRG No </option>

                                        </select>

                                    </td>
 
                                    <td style="width:20%">

                                        <select class="form-control clearData select2" id="ddlDUNo" data-placeholder="Select DU No" style="width:100%; ">

                                            <option value="" selected="selected"> Select DU No </option>

                                        </select>

                                    </td>
 
                                    @if (ViewBag.UserRole != null)

                                    {

                                        if (ViewBag.UserRole == "AuxilliaryUser")

                                        {

                                            <td>

                                                <span id="totaldrgqty"></span>

                                            </td>

                                            <td style="display: none">

                                                <span id="lblDRGBalanceQTY"></span>

                                            </td>

                                        }

                                        else

                                        {

                                            <td style="display: none">

                                                <span id="totaldrgqty"></span>

                                            </td>

                                            <td>

                                                <span id="lblDRGBalanceQTY"></span>

                                            </td>

                                        }

                                    }

                                    <td>

                                        <span id="lblAuxGBalanceQTY"></span>

                                    </td>

                                    @if (ViewBag.UserRole != null)

                                    {

                                        if (ViewBag.UserRole == "AuxilliaryUser")

                                        {

                                            <td>

                                                <span id="LogAvaQty"></span>

                                            </td>
 
                                        }

                                        else

                                        {

                                            <td style="display: none">

                                                <span id="LogAvaQty"></span>

                                            </td>

                                        }

                                    }

                                    <td>

                                        <input type="text" id="txtQty" class="form-control" placeholder="Qty" oninput="validateInput(this)" />

                                    </td>

                                    <td>

                                        <input type="text" id="txtRemarks" class="form-control" placeholder="Remarks" />

                                    </td>

                                    <td><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">Delete</button></td>

                                </tr>

                            </tbody>*@

                    </table>

Solution

  • You said datatables but I'm not seeing anything in your code that points to using the jquery library "datatables". If you are, then that's not how you add row data at all. If not and just creating your own, you can simplify row deletion with no need for a unique id.

    Also, specifically to your code, you push IDs to uniqueRowIds but you never remove them after deleting a row. Is that intentional?

    $('#mytable').on('dblclick', 'tr', e => {
        
      $(e.currentTarget).remove();
     
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <table id="mytable" border="1">
      <tr><td>1</td><td>foo</td><td>bar</td></tr>
      <tr><td>2</td><td>lorem</td><td>ipsum</td></tr>
      <tr><td>3</td><td>bugs</td><td>bunny</td></tr>
      <tr><td>4</td><td>zero</td><td>cool</td></tr>
    </table>