【问题标题】:Datatables JQuery Adding new row - not workingDatatables JQuery添加新行 - 不起作用
【发布时间】:2020-04-15 10:27:08
【问题描述】:

HTML:

        <div class="datatable-header">
             <button type="button" name="add" id="add" class="float-right btn btn-info">Add</button>
         </div>

        <div class="table-responsive">
            <table class="table datatable-basic table-striped table-hover table-bordered"
                   data-data-url="<?= $this->url('bla/blabla/ajax', ['action' => 'list']) ?>
                   id="text-dataTable"
            >
                <thead>
                <tr>
                    <th>Text</th>
                    <th>Actions</th>
                 </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>

jQuery:

 const textTable = $('#text-dataTable');
        const textDataTable = textTable.DataTable({
            "lengthMenu": [[10, 25, 50, 75, -1], [10, 25, 50, 75, "All"]],
            "dom": '<"top"fBr><"datatable-scroll-wrap"t><"bottom mt-2"ilp>',
            "lengthChange": true,
            "pageLength": 25,
            "autoWidth": false,
            "searching": false,
            "order": [[0, 'asc']],
            "ajax": {
                "url": textTable.data('data-url'),
                "type": "POST"
            },
            "columnDefs": [
                { targets: [1], className: "text-center"},
            ],
            "columns": [
                { data: "text", "render": function (data, type, full, meta) {
                        return '<textarea style="width: 100%"  contenteditable id="text" class="update" data-id="'+full.id+'" data-column="text">' + data + '</textarea>';
                    }
                },
                { data: "textId", "render": function (data, type, full, meta) {
                        let $html =  '<a class="btn bg-success m-1 update" data-id="'+data+'"><i class="icon-floppy-disk"></i> Update</a>';
                         $html +=  '<a class="btn bg-danger m-1 remove" data-id="'+data+'"><i class="icon-trash"></i> Delete</a>';
                         $html +=  '<a class="btn bg-grey m-1 reset" data-id="'+data+'"><i class="icon-reset"></i> Reset</a>';
                         return $html;
                    }
                },
            ],
            "rowCallback": function (row, data, index) {
                if (data.hasOwnProperty('rowClass')) {
                    $(row).attr('class', data.rowClass);
                }

                $('td:last', row).attr('class', 'text-center');
                }
        });

        $('#add').click(function(){
            const addedRow = textDataTable.row.add(
                {
                    "text": "aa",
                    "textId": "bb",
                }
           );
            textDataTable.draw( false );
            const addedRowNode = addedRow.node();
            $(addedRowNode).addClass('highlight');
        });

结果: 它正在更新第一列的文本和第二列的数据ID,我的目标是添加一个新的空行,这意味着我希望第一列具有'aa',而第二列具有'bb'的按钮。我徒劳地尝试了数百件事。

见截图:

我尝试的第二件事:这是一个问题,因为如果用户同时添加多行并单击逐个插入,它将始终插入添加的第一个新行的值,因为它是通过 id 获取值.并且所有新行都具有相同的 ID。


      $('#add').click(function(){

            let html = '<tr>';
            html += '<td><textarea contenteditable id="new-row-text">aa</textarea></td>';
            html += '<td><a class="btn bg-grey m-1 insert"><i class="icon-plus22"></i> Insert</a></td>';
            html += '</tr>';
            $('#text-dataTable tbody').prepend(html);
        });

        textDataTable.on('click', 'a.insert', function(){

            swal.fire({
                title: 'Are You Sure?',
                showCancelButton: true,
                confirmButtonClass: "btn-success",
                reverseButtons: true,
                showLoaderOnConfirm: true,
                preConfirm: function (data) {
                    return new Promise(function (resolve, reject) {
                        $.post(
                            textDataTable.data('insert-url'),
                            {
                                text: $('#new-row-text').val()
                            },
                            (function data($data) {
                                resolve()
                            }),
                            'json'

                        ).fail((function(xhr, status, error) {
                            swal.fire('Error', xhr.responseJSON.error, 'error');

                        }));
                    })
                }

            }).then(result => {
                if (result.value) {
                    textDataTable.ajax.reload();
                } else {
                }
            }, (function () {

            }));

        });

【问题讨论】:

  • 你可以用append代替addapi.jquery.com/append
  • @Reza 我需要添加一行,因为我需要将其插入数据库,并且我需要从行的数据中获取文本的值,因为如果我附加 html 然后获取这样的值: $('.new-text').val() ,如果我同时添加多个新行,那将是错误的,因为通过 id 或 class 获取值,将获得第一行的值已添加
  • 与问题无关:$(row).attr('class', 应该是$(row).addClass((在大多数情况下) - 在“rowCallback”中,您设置类然后立即覆盖它 - 如果您使用 addClass,它将同时具有(如果你不希望两者都应该是一个'else')
  • @freedomn-m 是的,不幸的是这不是原因
  • 请确认:当您添加新行(通过 .row.add 到数据表数据库)时,您希望它与其他行以不同方式显示吗?现有行:input+buttons,新行:input+"bb"?

标签: javascript jquery html ajax datatables


【解决方案1】:

解决办法:

const addedRow = textDataTable.row.add(
 {
     "text": "aa",
     "textId": "bb",
     "newRow": true
 }

);

然后在render函数中测试一下newRow标志是否存在:

{ data: "textId", "render": function (data, type, full, meta) {
        // Return data if new row
        if (full.hasOwnProperty('newRow') {
          return data;
        }
.
.
},

信用用户2Fkthorngren:https://datatables.net/forums/discussion/61522/problem-with-adding-new-empty-row/p1?new=1

【讨论】:

  • 仅供参考:如果.row.add({"newRow":false})if (full.hasOwnProperty('newRow') 也将是真的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多