将克隆行附加到单击按钮的最新子项

问题描述 投票:0回答:1

我有一个带有按钮的表,单击该按钮后,我通过 AJAX 将其保存在数据库中。如果成功,它应该克隆按钮所在的当前行,然后将其附加到最新的子项。将其保存在数据库中没有问题。我的问题纯粹是前端。

这是我的示例表:

no.     | button holder
-----------------------
2       | button here |
---------------------
2.1     | button here |
-----------------------
2.1.1   | button here |
-----------------------
2.1.1.1 | button here |
-----------------------
2.1.1.2 | button here |
-----------------------
2.2     | button here |
-----------------------
2.2.1   | button here |
-----------------------
2.2.2   | button here |
-----------------------
2.3     | button here |
-----------------------

我想涵盖的场景:

  • 如果我单击 2 旁边的按钮,我应该能够创建 2.4 并将其添加到 2.3 之后,因为 2 的最后一个子级是 2.3
  • 如果我单击 2.1.1 旁边的按钮,我应该能够创建 2.1.1.3 并将其添加到 2.1.1.2 之后,因为 2.1.1 的最后一个子级是 2.1.1.2
  • 如果我单击 2.3 旁边的按钮,我应该能够创建 2.3.1 并将其添加到 2.3 之后,因为 2.3 还没有子级。

第一级儿童有

tr class = parent
指示,其余儿童有
tr class = child

这是我当前的功能:

var currentButton;
var labelName;
var button_from;
function addChild(is_initial){
    labelName = $('#childlabelName').val();
    //ajax to save the new child
    if(button_from == 'td'){
        parent_id = child_id;
    }
    $.ajax({
        method: 'post',
        dataType: 'json',
        data:{'get_action':'add_child', 'header_id':header_id, 'parent_id': parent_id, 'row_content': labelName},
        success:function(response){
            if(response.success == true){
                $.confirm({
                    title: 'Success!',
                    content: 'Successfully added the new child.',
                    type: 'green',
                    typeAnimated: true,
                    buttons: {
                        close: function () {
                            if(button_from == 'th'){ //if button is clicked from the header
                                // Find the closest thead
                                var $thead = $(currentButton).closest('thead');
                                // Find the next tbody after this thead
                                var $nextTbody = $thead.next('tbody');

                                // Find the last row in the tbody
                                var $lastRow = $nextTbody.find('tr:last');

                                // Clone the last row
                                var $clonedRow = $lastRow.clone();

                                // Get the current row number from the last row's text
                                var lastRowNumberText = $lastRow.find('td:first').text();
                                var lastRowNumberParts = lastRowNumberText.split('.');
                                var newNumber = parseInt(lastRowNumberParts[1]) + 1;

                                // Update the number in the first td of the cloned row
                                var newNumberText = lastRowNumberParts[0] + '.' + newNumber;
                                $clonedRow.find('td:first').text(newNumberText);

                                // Optional: Clear input values in the cloned row
                                $clonedRow.find('input, textarea').val('');

                                // Get the header index
                                var get_index = $thead.index() / 2; // Assuming thead and tbody are alternating

                                // Get the index of the latest cloned row
                                var indexOfLatestRow = $nextTbody.find('tr').length;

                                // Update the label in the second td of the cloned row
                                var second_column_content = labelName +
                                    '<div class="mt-1 btn-holder d-flex align-items-center">' + 
                                        '<button data-id="' + response.row_id + '" data-header_id="' + header_id + '" data-parent_id="' + parent_id + '" onclick="loadModal(this,\'table\',false);" type="button" class="btn btn-link add-sign px-0 fw-bold">(<span class="plus-sign">+</span>Add Child)</button>' + 
                                    '</div>';

                                $clonedRow.find('td:eq(1)').html(second_column_content);
                                // Update the names and IDs of form elements in the cloned row
                                $clonedRow.find('input, textarea').each(function() {
                                    var old_name = $(this).attr('name');
                                    var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id); // Replace the last part after underscore with row_id
                                    $(this).attr('name', new_name);
                                });

                                // Add a delete button in the cloned row
                                //$clonedRow.find('td:last').html('<i class="bi bi-trash-fill" onclick="delete_current_row(this);" style="font-size: 20px; color: red;"></i>');
                                clearFields($clonedRow);
                                // Append the cloned row to the correct tbody
                                $nextTbody.append($clonedRow);
                            }

                            if (button_from == 'td') {
                                var $closestTr = $(currentButton).closest('tr');
                                var $lastRowWithParentId = null;
                                var foundChild = false;

                                // Find the last row with the same parent_id
                                $closestTr.nextAll('tr').each(function() {
                                    var $tdWithButton = $(this).find('td:eq(1)');
                                    if ($tdWithButton.find('button').data('parent_id') == parent_id) {
                                        $lastRowWithParentId = $(this);
                                        foundChild = true;
                                    } else if (foundChild) {
                                        return false; // break loop if a non-child row is found after finding a child
                                    }
                                });

                                // If no row with the same parent_id is found, find the row with data-id = parent_id
                                if (!$lastRowWithParentId) {
                                    $closestTr.nextAll('tr').each(function() {
                                        var $tdWithButton = $(this).find('td:eq(1)');
                                        if ($tdWithButton.find('button').data('id') == parent_id) {
                                            $lastRowWithParentId = $(this);
                                            return false; // break loop once found
                                        }
                                    });
                                }

                                // Clone the row
                                var $rowToClone = $lastRowWithParentId ? $lastRowWithParentId : $closestTr;
                                var $clonedRow = $rowToClone.clone();

                                if ($closestTr.hasClass('parent')) {
                                    $clonedRow.closest('tr').attr('class', 'child');
                                }

                                // Update hierarchical number
                                var newHierarchicalNumber = getNewHierarchicalNumber($rowToClone.find('td:first').text(), $closestTr);
                                $clonedRow.find('td:first').text(newHierarchicalNumber);
                                $clonedRow.find('input, textarea').val('');

                                // Update the label in the second td of the cloned row
                                var second_column_content = labelName +
                                    '<div class="mt-1 btn-holder d-flex align-items-center">' +
                                    '<button data-id="' + response.row_id + '" data-header_id="' + header_id + '" data-parent_id="' + parent_id + '" onclick="loadModal(this,\'table\',false);" type="button" class="btn btn-link add-sign px-0 fw-bold">(<span class="plus-sign">+</span>Add Child)</button>' +
                                    '</div>';

                                $clonedRow.find('td:eq(1)').html(second_column_content);

                                $clonedRow.find('input, textarea').each(function() {
                                    var old_name = $(this).attr('name');
                                    var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id);
                                    $(this).attr('name', new_name);
                                });

                                // Insert the cloned row after the last row with the same parent_id or the current row
                                if ($lastRowWithParentId) {
                                    $lastRowWithParentId.after($clonedRow);
                                } else {
                                    $closestTr.after($clonedRow);
                                }
                            }
                        }
                    }
                });
            } else {
                $.confirm({
                    title: 'Encountered an error!',
                    content: 'Failed to add the new child. Please refresh the page and try again. Contact the system\'s administrator if issue persists.',
                    type: 'red',
                    typeAnimated: true,
                    buttons: {
                        close: function () {
                        }
                    }
                });
            }
        }
    });
    $('#childlabelName').val('');
    
}

function getNewHierarchicalNumber(currentNumber, $closestTr) {
    var hierarchicalParts = currentNumber.split('.');
    var parentNumberParts = $closestTr.find('td:first').text().split('.');

    if (parentNumberParts.length >= hierarchicalParts.length) {
        hierarchicalParts = parentNumberParts;
    } else {
        // If the current number is shorter, assume it's a direct child and add a level
        hierarchicalParts.push(0);
    }

    hierarchicalParts[hierarchicalParts.length - 1] = parseInt(hierarchicalParts[hierarchicalParts.length - 1]) + 1;
    return hierarchicalParts.join('.');
}

我真正想解决的是:

  • 编号
  • 克隆行的放置

非常感谢任何帮助。

jquery ajax frontend codeigniter-3
1个回答
0
投票

我想我得工作了。这是我更新的功能:

var currentButton;
var labelName;
var button_from;
function addChild(is_initial){
    labelName = $('#childlabelName').val();
    //ajax to save the new child
    if(button_from == 'td'){
        parent_id = child_id;
    }
    $.ajax({
        method: 'post',
        dataType: 'json',
        data:{'get_action':'add_child', 'header_id':header_id, 'parent_id': parent_id, 'row_content': labelName},
        success:function(response){
            if(response.success == true){
                $.confirm({
                    title: 'Success!',
                    content: 'Successfully added the new child.',
                    type: 'green',
                    typeAnimated: true,
                    buttons: {
                        close: function () {
                            if(button_from == 'th'){ //if button is clicked from the header
                                // Find the closest thead
                                var $thead = $(currentButton).closest('thead');
                                // Find the next tbody after this thead
                                var $nextTbody = $thead.next('tbody');

                                // Find the last row in the tbody
                                var $lastRow = $nextTbody.find('tr:last');

                                // Clone the last row
                                var $clonedRow = $lastRow.clone();

                                // Get the current row number from the last row's text
                                var lastRowNumberText = $lastRow.find('td:first').text();
                                var lastRowNumberParts = lastRowNumberText.split('.');
                                var newNumber = parseInt(lastRowNumberParts[1]) + 1;

                                // Update the number in the first td of the cloned row
                                var newNumberText = lastRowNumberParts[0] + '.' + newNumber;
                                $clonedRow.find('td:first').text(newNumberText);

                                // Optional: Clear input values in the cloned row
                                $clonedRow.find('input, textarea').val('');

                                // Get the header index
                                var get_index = $thead.index() / 2; // Assuming thead and tbody are alternating

                                // Get the index of the latest cloned row
                                var indexOfLatestRow = $nextTbody.find('tr').length;

                                // Update the label in the second td of the cloned row
                                var second_column_content = labelName +
                                    '<div class="mt-1 btn-holder d-flex align-items-center">' + 
                                        '<button data-id="' + response.row_id + '" data-header_id="' + header_id + '" data-parent_id="' + parent_id + '" onclick="loadModal(this,\'table\',false);" type="button" class="btn btn-link add-sign px-0 fw-bold">(<span class="plus-sign">+</span>Add Child)</button>' + 
                                    '</div>';

                                $clonedRow.find('td:eq(1)').html(second_column_content);
                                // Update the names and IDs of form elements in the cloned row
                                $clonedRow.find('input, textarea').each(function() {
                                    var old_name = $(this).attr('name');
                                    var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id); // Replace the last part after underscore with row_id
                                    $(this).attr('name', new_name);
                                });

                                // Add a delete button in the cloned row
                                //$clonedRow.find('td:last').html('<i class="bi bi-trash-fill" onclick="delete_current_row(this);" style="font-size: 20px; color: red;"></i>');
                                clearFields($clonedRow);
                                // Append the cloned row to the correct tbody
                                $nextTbody.append($clonedRow);
                            }

                            if (button_from == 'td') {
                                var $closestTr = $(currentButton).closest('tr');
                                var $lastRowWithParentId = null;
                                var foundChild = false;

                                // Find the last row with the same parent_id
                                $closestTr.nextAll('tr').each(function() {
                                    var $tdWithButton = $(this).find('td:eq(1)');
                                    if ($tdWithButton.find('button').data('parent_id') == parent_id) {
                                        $lastRowWithParentId = $(this);
                                        foundChild = true;
                                    } else if (foundChild) {
                                        return false; // break loop if a non-child row is found after finding a child
                                    }
                                });

                                // If no row with the same parent_id is found, find the row with data-id = parent_id
                                if (!$lastRowWithParentId) {
                                    $closestTr.nextAll('tr').each(function() {
                                        var $tdWithButton = $(this).find('td:eq(1)');
                                        if ($tdWithButton.find('button').data('id') == parent_id) {
                                            $lastRowWithParentId = $(this);
                                            return false; // break loop once found
                                        }
                                    });
                                }

                                // Clone the row
                                var $rowToClone = $lastRowWithParentId ? $lastRowWithParentId : $closestTr;
                                var $clonedRow = $rowToClone.clone();

                                if ($closestTr.hasClass('parent')) {
                                    $clonedRow.closest('tr').attr('class', 'child');
                                }

                                // Update hierarchical number
                                var newHierarchicalNumber = getNewHierarchicalNumber($rowToClone.find('td:first').text(), $closestTr);
                                $clonedRow.find('td:first').text(newHierarchicalNumber);
                                $clonedRow.find('input, textarea').val('');

                                // Update the label in the second td of the cloned row
                                var second_column_content = labelName +
                                    '<div class="mt-1 btn-holder d-flex align-items-center">' +
                                    '<button data-id="' + response.row_id + '" data-header_id="' + header_id + '" data-parent_id="' + parent_id + '" onclick="loadModal(this,\'table\',false);" type="button" class="btn btn-link add-sign px-0 fw-bold">(<span class="plus-sign">+</span>Add Child)</button>' +
                                    '</div>';

                                $clonedRow.find('td:eq(1)').html(second_column_content);

                                $clonedRow.find('input, textarea').each(function() {
                                    var old_name = $(this).attr('name');
                                    var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id);
                                    $(this).attr('name', new_name);
                                });

                                // Insert the cloned row after the last row with the same parent_id or the current row
                                if ($lastRowWithParentId) {
                                    $lastRowWithParentId.after($clonedRow);
                                } else {
                                    $closestTr.after($clonedRow);
                                }
                            }
                        }
                    }
                });
            } else {
                $.confirm({
                    title: 'Encountered an error!',
                    content: 'Failed to add the new child. Please refresh the page and try again. Contact the system\'s administrator if issue persists.',
                    type: 'red',
                    typeAnimated: true,
                    buttons: {
                        close: function () {
                        }
                    }
                });
            }
        }
    });
    $('#childlabelName').val('');
    
}

function getNewHierarchicalNumber(currentNumber, $closestTr) {
    var hierarchicalParts = currentNumber.split('.');

    // Find all child rows of $closestTr
    var $childRows = $closestTr.nextUntil('tr:not(.child)');
    
    // If there are child rows, find the last one and increment its number
    if ($childRows.length > 0) {
        var lastChildNumber = $childRows.last().find('td:first').text();
        var lastChildNumberParts = lastChildNumber.split('.');
        hierarchicalParts = lastChildNumberParts;
        hierarchicalParts[hierarchicalParts.length - 1] = parseInt(hierarchicalParts[hierarchicalParts.length - 1]) + 1;
    } else {
        // If no child rows, append ".1" to the current hierarchical number
        hierarchicalParts.push('1');
    }

    return hierarchicalParts.join('.');
}

我刚刚添加了另一个条件,如果单击按钮的当前行下没有现有的子项,则应该复制克隆的数字并向其添加“.1”。

如果您发现我的代码有问题,请随时发表评论。

© www.soinside.com 2019 - 2024. All rights reserved.