noob-fella noob-fella -4 years ago 583
jQuery Question

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.

I found this sample working perfeclty here. But i could not apply in my sample here in my 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>




Answer Source


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.

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. 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.

 $('#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!

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download