简体   繁体   English

jQuery Datatable如何编辑,保存和添加新行

[英]Jquery Datatable how to edit, save and add a new row

I am trying make the rows from table 1 , editable as well i would like add a new row too. 我正在尝试使表1中的行可编辑以及我也想添加新行。

I found this sample working perfeclty here . 我在这里发现此示例工作正常。 But i could not apply in my sample here in my jsfiddle 但是我无法在我的jsfiddle中将其应用于示例

Iam pasting the working sample as snippet here below 我将工作样本粘贴为以下代码段

 function addUser() { var $source = $("#example2").DataTable(); var names = $($source.rows().nodes()) .filter(':has(:checked)') .map(function() { return $(this).children().first().text(); }).toArray(); console.log(names); var $rows = $source.rows(function(i, data) { return names.indexOf('' + data.name) != -1; }); var data = $rows.data(); if (data.length > 0) { $rows.remove().draw(); $("#example").DataTable().rows.add(data.toArray()).draw(); } } function checkAll(check) { $('#chk').prop('checked', check == 1); var $source = $("#example2").DataTable(); var names = $($source.rows().nodes()) .find('input[type="checkbox"]') .each(function(i, el) { el.checked = check == 1; }); return false; } function all() { var a = 0; var $source = $("#example2").DataTable(); var names = $($source.rows().nodes()) .find('input[type="checkbox"]') .each(function(i, el) { if (el.checked) { a++ } console.log(a); }); if (a == 5) { $('#chk').prop('checked', true); } else { $('#chk').prop('checked', false); } } $(document).ready(function() { var dt = $('#example').dataTable(); dt.fnDestroy(); }); $(document).ready(function() { var url = 'http://www.json-generator.com/api/json/get/cvQJpCWCuW?indent=2'; var table = $('#example').DataTable({ ajax: url, createdRow: function(row, data, dataIndex) { $(row).attr('id', 'row-' + dataIndex); }, rowReorder: { dataSrc: 'order', }, columns: [{ data: 'name' }, { data: 'name' }, { data: 'place' }] }); table.rowReordering(); }); $(document).ready(function() { var dt = $('#example2').dataTable(); dt.fnDestroy(); }); $(document).ready(function() { var url = 'http://www.json-generator.com/api/json/get/cnmZgfsBKa?indent=2'; var table = $('#example2').DataTable({ ajax: url, createdRow: function(row, data, dataIndex) { $(row).attr('id', 'row-' + dataIndex); }, rowReorder: { dataSrc: 'order', }, columns: [{ data: 'name' }, { data: 'checkbox' }] }); table.rowReordering(); }); $(document).ready(function() { $('#example2').on('click', 'input[type="checkbox"]', function() { all(); }); $('body').on('mouseenter', 'input', function() { $('.btn').prop('disabled', true); }); $('body').on('mouseout', 'input', function() { $('.btn').prop('disabled', false); }); $('#chk').on('change', function() { console.log($(this)); if ($(this)[0].checked) { checkAll(1); } else { checkAll(0); } }); $('#checkAll').click(function() { checkAll(1); }); $('#uncheckAll').click(function() { checkAll(0); }); $('#btnAddUser').click(function() { addUser(); }); }); 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> <script src="//cdn.rawgit.com/DataTables/RowReorder/ce6d240e/js/dataTables.rowReorder.js"></script> <link href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" /> <link href="//cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" rel="stylesheet" /> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <br> <br> <h1> table1 </h1> <br> <br> <table id="example" class="display" width="100%" cellspacing="0"> <thead> <tr> <th>First name</th> <th>Place</th> <th>Order</th> </tr> </thead> </table> <br> <br> <h1> table 2 </h1> <br> <br> <table id="example2" class="display" width="100%" cellspacing="0"> <thead> <tr> <th>Place</th> <th>checkbox</th> </tr> </thead> </table> <div class="col-md-12"> <div class="col-md-6"> <button type="button" class="btn btn-success" id="btnAddUser">Add a user</button> </div> <div class="col-md-6">select all or none <div class="btn-group"> <div class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <input type="checkbox" name="vehicle1" value="Bike" id="chk"> <i class="fa fa-caret-down" aria-hidden="true"></i> </div> <ul class="dropdown-menu" role="menu"> <li><a id="checkAll">All</a></li> <li><a id="uncheckAll">None</a></li> </ul> </div> </div> </div> 


It's funny to see fiddles I have made for old questions are starring in new questions. 看到我对旧问题所做的小提琴正在出现新问题时,这很有趣。

Anyway, I have made a plunker for you, it's working. 无论如何,我为您制作了一个小品,它正在工作。 Take the dataTables.rowReorder.js file to your project, I modified it to support input editing. dataTables.rowReorder.js文件带到您的项目中,我对其进行了修改以支持输入编辑。

Few things that I added to this plunker: The add row function will iterate over TABLE2 and will select the rows with the checked checkboxes and will add them to TABLE1 and remove them from TABLE2. 我添加到此插件的一些内容:添加行功能将遍历TABLE2,并选择带有选中复选框的行,并将其添加到TABLE1中并将其从TABLE2中删除。 It takes the name value of the selected row, and default value Some Country you can debug it and take whatever piece of data you want for your table. 它采用所选行的name值,以及默认值“ Some Country您可以对其进行调试,并获取所需的表数据。

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

        var rowsHtml; 
        var $newRowTemplate = $("#newRow").find("tr");

        table2.rows().every(function(rowIdx, tableLoop, rowLoop) {

          var row = this.node();
          var isChecked = $(row).find("input[type='checkbox']").prop("checked");

          if (isChecked) {
            $newRowTemplate.find("td:first").text(table.rows().count() + 1);
            $newRowTemplate.find("input[name='name']").attr("value",this.data().name);
            $newRowTemplate.find("input[name='country']").attr("value","Some Country");

            rowHtml = $newRowTemplate[0].outerHTML;  
            table.row.add($(rowHtml)).draw();

            $(row).addClass("remove");

          }

        });

        table2.rows(".remove").remove().draw();

      });

I also fixed the search functionality that you supplied in your "working fiddles", the search there wasn't working for new added rows, mine works and it's because there is a need to update the table.cell.data() and not only the html of the datatables, this is IMPORTANT! 我还修复了您在“工作小提琴”中提供的搜索功能,该搜索不适用于新添加的行,我的工作也table.cell.data() ,这是因为需要更新table.cell.data()不仅数据表的html,这很重要!

You can see it in the save function: 您可以在保存功能中看到它:

 $("#example").on('mousedown.save', "i.fa.fa-envelope-o", function(e) {

        $(this).removeClass().addClass("fa fa-pencil-square");

        var $row = $(this).closest("tr");
        var $tds = $row.find("td").not(':first').not(':last');

        $.each($tds, function(i, el) {
          var txt = $(this).find("input").val();
          $(this).html(txt);

          //This is where I update the cell data with the new value
          table.cell(this).data(txt);
        });

        var $firstTdSelect = $row.find("td:first");
        var selectValue = $firstTdSelect.find("select").val();
        $row.find("td:first").html(selectValue);

        //This is where I update the cell data with the new value            
        table.cell($firstTdSelect).data(selectValue);

      });

You asked in your question for adding new rows, editing rows and I added a few more stuff, Don't complain that the "Save All" and "Cancel" button are not there, because you can't ask from users here to do all the job for you, take this plunker that already contains all the code you need for the "Save all" button and try to solve it by your self, if you won't succeed post a new question. 您在问题中问过要添加新行,编辑行,而我又添加了一些其他内容,请不要抱怨“保存全部”和“取消”按钮不存在,因为您不能要求此处的用户这样做为您完成所有工作,请使用已经包含“全部保存”按钮所需代码的所有代码,如果您无法成功发布新问题,请尝试自行解决。

Check out this Working Plunk . 看看这个Working Plunk

I made a fully editable table (add, edit, delete) using datatables and jquery. 我使用datatables和jquery制作了一个完全可编辑的表(添加,编辑,删除)。 Its located here http://jsbin.com/yafuvah/edit?html,css,js,output if you want to play with it. 如果您想使用它,它位于此处http://jsbin.com/yafuvah/edit?html,css,js ,输出。 I had a version that used checkbox but this version uses the select rows extension set to single row. 我有一个使用复选框的版本,但是此版本使用选择行扩展名设置为单行。

   var dataObject = null;

    $(document).ready(function () {
        var table = $('#example').DataTable({
            buttons: [{
              text: "Edit", className :"editButton",
                extend: "selectedSingle",
                action: function (e, dt, bt, config) { editRow(e, dt, bt, config); }
            }, {
                text: "Save",
                extend: "selectedSingle",
                action: function (e, dt, bt, config) { saveRow(e, dt, bt, config); }
            }, {
                text: "Add",
                action: function (e, dt, bt, config) { addRow(e, dt, bt, config); }
            }, {
                text: "Delete",
                extend: "selectedSingle",
                action: function (e, dt, bt, config) { removeRow(e, dt, bt, config); }
            }],
            dom: "Btp",
            select: "single"
        });

        var dataObject = table.rows().data();

        // keep the rows from deselection when you click on a textbox
        // this means you have to click between textboxes to change edit rows when more than one is onpen
        $("#example").on("click", "input", function (e) { e.stopPropagation(); return false; });

        table.on('user-select', function (e, dt, type, cell, originalEvent) {
            if ($('#example input').length > 0) {
                e.preventDefault();
                return false;
            }
        });
    });

    // Adds a new row in edit mode
    function addRow(e, dt, bt, config) {
        if ($('#example input').length > 0) {
            // only one row is allowed to be in edit mode at a time
            return false;
        }
        var $nr = dt.row.add(["", "", "", "", "", ""]).draw(false).nodes().to$();
      $nr.addClass("newRow");
        dt.rows($nr).select();
        $nr.children("td").each(function (i, it) {
            $(it).append("<input type='text'>");
        });
      $(".editButton span").text("Cancel");
      // Puts 
      dt.page("first").draw();
    }

     function removeRow(e, dt, bt, config){
          var r = dt.rows(".selected").nodes()[0];
       var n = $("td:first", r).text();
       if(!confirm("You are about to remove " + n)){return;}
        dt.rows(".selected").remove().draw();
     }

    // Save the selected row (assuming its in edit mode)
    function saveRow(e, dt, bt, config) {
        var r = dt.rows(".selected").nodes()[0];

        // if row is not edit mode, just return.
        if ($("input", r).length === 0) { return; }


        var d = dt.rows(".selected").data()[0];
        var containsText = false;
        $(r).children("td").each(function (i, it) {
            var di = $("input", it).val();
            if (di.length > 0) { containsText = true; }
            $(it).html(di);
            d[i] = di;
        });
        if (!containsText) {
            alert("This row contains no data and will be removed");
            dt.rows(".selected").remove().draw();
        }
      $(".editButton span").text("Edit");
    }

    // Puts a row in edit mode
    function editRow(e, dt, bt, config) {
       var r = dt.rows(".selected").nodes()[0];
     if(  $("span", bt[0]).text() == "Cancel"){

       if($(r).hasClass("newRow")){
          dt.rows(".selected").remove().draw();
       }
       else {
       $(r).children("td").each(function (i, it) {
            var od = dt.cells(it).data();
            $(it).html(od[0]);
        });
       } 

       $("span", bt[0]).text("Edit");
       return;
     }

        // if row already in edit mode, just return.
        if ($("input", r).length > 0) { return; }

        $(r).children("td").each(function (i, it) {
            var h = $("<input type='text'>");
            h.val(it.innerText);
            $(it).html(h);
        });
      $("span", bt[0]).text("Cancel");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM