Datatable показывает пустые данные в строке - PullRequest
0 голосов
/ 19 сентября 2018

У меня есть таблица данных, которая имеет две строки. Первая строка comign непосредственно для БД и отображается в пользовательском интерфейсе.Вторая строка добавляется с помощью метода addRow в javascript.Пожалуйста, посмотрите код ниже:

Вот строка таблицы в источнике html:

enter image description here

А вот код для доступа к строке:

 var table = "";

 table = $("#orders").DataTable({
                ajax: {
                    url: "/api/dfddsfs?id="+ id,
                    dataSrc: ""
                },
                columns: [
                    {

                        data: "product.description",
                    },
                    {

                        data: "quantity"
                    },
                    {

                        data: "product.productPrice"
                    },
                    {
                        data: "discount"
                    },
                    {
                        data: "product.isTaxable"
                    },
                    {
                        data: "finalPrice"
                    },
                    {
                        data: "lineItemTotal"
                    },
                    {
                        data: "product.description",
                        render: function (data, type, product) {

                            return "<span class='glyphicon glyphicon-trash js-delete' data-lineitem-id=" + data + "></span>";


                        }
                    }
                ]
            });


 $('#addRow').click(function () {
    if ($("[name='Product.description']").valid()) {
        //Create a row if not null
        var rowHtml = $("#newRow").find("tr")[0].outerHTML;
        //Add row to the table
        $('#orders').DataTable().row.add($(rowHtml)).draw();
        //Set the first column to product description
        $('#orders tr:first-child td:first-child').first().html($("#product").val());
        //Set second column to quantity
        $('#orders tr:first-child td:nth-child(2)').append("2");

        //Set third column to price
        $('#orders tr:first-child td:nth-child(3)').first().html("123");
       //Set fourth column to dicount
        $('#orders tr:first-child td:nth-child(4)').append("10");
        //Set fifth column as a checkbox
        $('#orders tr:first-child td:nth-child(5)').append("<label><input type='checkbox' value=''></label>");
        //clear the product input text
        $('#product').val('');
    }
    else
        alert("Please choose a product");
});




     $('#save').click(function (evt) {

           table.rows().every(function (rowIdx, tableLoop, rowLoop) {
                   var data = this.data();
                   console.log("data is " + JSON.stringify(data));
            });

      });

Вот результат консоли:

data is <br/>
data is {"product":{"description":"","productPrice":"","isTaxable":""},"quantity":"","discount":"","finalPrice":"","lineItemTotal":""}
8:352 data is {"delete":"<i class='fa fa-pencil-square' aria-hidden='true'></i> <i class='fa fa-minus-square .js-delete' aria-hidden='true'></i>","id":21,"quantity":12,"discount":12,"product":{"id":501,"upc":null,"description":"Eggs","restockQty":26,"productPrice":40000,"isTaxable":false,"productCost":11000,"image":"","productCode":"01 B 04","packing":20,"productWholesalePrice":20000},"productId":501,"salesOrder":null,"salesOrderId":8,"lineTaxes":9,"isTaxable":true,"lineItemTotal":999,"finalPrice":9999}

Как видите, результат отображается для объектов данных.Один со значениями и один без значений.

1 Ответ

0 голосов
/ 19 сентября 2018

Вы снова звоните .DataTable() внутри нажатия кнопки сохранения.Вы должны инициализировать datatable вне нажатия кнопки, сохранить его в переменной и использовать его для перебора строк

var table = $('#orders').DataTable();// store previously initialised datatable in variable

$('#save').click(function (evt) {
      //var table = $('#orders').DataTable(); -- remove it
       table.rows().every(function (rowIdx, tableLoop, rowLoop) {
               var data = this.data();
               console.log("data is " + JSON.stringify(data));
        });

  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...