Bootstrap Table Add Update Delete
by jimkennelly
HTML
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.css">
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<div id="tableContainer">
<table id="table">
<thead>
<tr>
<th data-field="id" data-formatter="formatUpdate">Update</th>
<th data-field="id" data-formatter="formatDelete">Delete</th>
<th data-field="id">id</th>
<th data-field="name">Name</th>
<th data-field="stargazers_count">Stars</th>
<th data-field="forks_count">Forks</th>
<th data-field="description">Description</th>
<th data-field="source">Source</th>
</tr>
</thead>
</table>
<a class="btn btn-default btnAddDeleteUpdate" data-operation="add" data-id="5">Add</a>
<a class="btn btn-danger btnSave">Save</a>
<a class="btn btn-danger btnUpdated">Get Updated</a>
<a class="btn btn-danger btnDeleted">Get Deleted</a>
<a class="btn btn-danger btnInserted">Get Inserted</a>
</div>
JavaScript
var originalData;
var deletedData;
var insertedData;
var updatedData;
$(function() {
$('#table').bootstrapTable({
url: 'https://api.myjson.com/bins/tpju3',
uniqueId: 'id',
}).on('load-success.bs.table', function(e, data) {
var d = $('#table').bootstrapTable('getData');
originalData = d.slice();
});
$("#tableContainer").on('click', '.btnDeleted', function() {
alert(JSON.stringify(deletedData));
// alert("aaaa");
});
$("#tableContainer").on('click', '.btnSave', function() {
var currentData = $("table").bootstrapTable('getData');
// deleted items
var props = ['id'];
var result = originalData.filter(function(o1) {
// filter out (!) items in result2
return !currentData.some(function(o2) {
return o1.id === o2.id; // assumes unique id
});
}).map(function(o) {
// use reduce to make objects with only the required properties
// and map to apply this to the filtered array as a whole
return props.reduce(function(newo, name) {
newo[name] = o[name];
return newo;
}, {});
});
alert('Deleted items = ' + JSON.stringify(result));
result = currentData.filter(function(o1) {
// filter out (!) items in result2
return !originalData.some(function(o2) {
return o1.id === o2.id; // assumes unique id
});
}).map(function(o) {
// use reduce to make objects with only the required properties
// and map to apply this to the filtered array as a whole
return props.reduce(function(newo, name) {
newo[name] = o[name];
return newo;
}, {});
});
alert('Inserted items = ' + JSON.stringify(result));
});
$("#myTable").on('click', '.btnAddDeleteUpdate', function() {
console.log($(this).text());
switch ($(this).data("operation")) {
case 'add':
var newRow = {
"source": "Inserted",
"id": "99",
"name": "bootstrap-ABC",
...