Copy Row Table into 'New Table'. | jQuery - javascript

I have created a dataTable copy row.
mainTable can only copy to the secondTable.
The problem is when adding New Table,
&
i want the mainTable row can copy into New Table.
i already create "Create New Table" button
New table will append into parent div allTable
MY JSFiddle.
Reference :
I want copy row into selected table(secondTable/newTable). not multiple. and I dont know how to add the selected button, because I'm using a variable.
I have parent div class="allTable" for Table/children (mainTable,
secondTable, and New Table).
i have "COPY ROW" for copy row table from mainTable to another Table, but now only work to copy into the secondTable.
In the $(document).ready(function()),
I have created dataTable for mainTable and secondTable.
mainTable ID is #table1
secondTable ID is #table2
New Table ID is #newTable + index (newTable(3) )
New Table will display blank data.
SCREENSHOT :
I really hope for your help.

This works, but you can improve it, I hope you can get the idea from here, this is not fully working as intended but the flow might help you.
https://jsfiddle.net/o6ysgzps/26/ I have updated the fiddle,
as you can see, I collected the list of tables that are created, and looped to each tables with a confirmation box to select which table you want it to be copied to., You can use bootstrap modal and jquery confirm to make it better,
You can make it cleaner,
html
<body>
<select id='cboList' style=''></select>
<div class="allTable">
<div class="one" style="padding-bottom:50px">
<h2>TABLE 1</h2>
<table id="table1" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<button id="Copy">COPY ROW »</button>
<!-- <button id="LeftMove" style="float:left;">« left</button> -->
<br>
<h2>TABLE 2</h2>
<div class="two">
<table id="table2" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<br>
<br>
<input type="button" class="submitButton" value="Create New Table">
<h2>NEW TABLE GOES HERE</h2>
</div>
</body>
This is the js
$(document).ready(function() {
var mainTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
}); // mainTable
var secondTable = $('#table2').dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // secondTable
mainTable.on('click', 'tbody tr', function() {
$(this).toggleClass('selected');
});
$('#Copy').on('click', function() {
var tables = $(".allTable").find("table*[id]").not("#table1");
tables.each(function(){
console.log(this.id);
var tbl_id = this.id;
var $elem = $(this);
var r = confirm("Copy to table "+tbl_id+"?");
var table_to_copy = $elem.dataTable();
if (r == true) {
copyRows(mainTable, table_to_copy);
alert("Copied!");
} else {
}
});
//
});
}); // end of $(document).ready...
function copyRows(fromTable, toTable) {
var $row = fromTable.find(".selected");
$.each($row, function(k, v) {
if (this !== null) {
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow); // <-- Copy Row
// fromTable.fnDeleteRow(this); <-- Move row, delete main row.
}
});
}
var tableIndex = 3;
$('.submitButton').click(function() {
let addIndex = tableIndex++;
var addTable = '<div class="newTable'+ addIndex +'">' +
'<table id="newTable'+ addIndex +'" class="table table-bordered table-hover">' +
'<thead>' +
'<tr>' +
'<th></th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'</tr>' +
'</thead>' +
'</table>' +
'</div>';
$('.allTable').append(addTable);
var newTable = $("#newTable"+ addIndex).dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // newTable
});

modify your code as follow:
function copyRows(fromTable, toTable) {
var toTable = $("table:last").dataTable(); // add this line to the function. Then you can remove toTable from parameters

Related

datatable column filtering with serverside(ajax) doesn't work (with django)

I'm developing with django and javascript with datatable.
I want to apply column filtering in my datatable
(https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html)
but it works fine without serverside option & ajax (in client side),
but it doesn't work with serverside option & ajax.
How can i FIX IT? Please help me..
this is my code.
<table id="sample_table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="sample_id">ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</thead>
<tbody id="sample_table_body">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
var column_list = [
{ "data" : "id" , "className": "sample_id"},
{ "data" : "receiving_at" },
{ "data" : "serialnumber" },
{ "data" : "name" },
{ "data" : "birthday" },
];
$('#sample_table tfoot th').each(function(){
var title = $("#sample_table thead th").eq( $(this).index() ).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
});
var sample_table = $('#sample_table').DataTable({
"paging": true,
"autoWidth": false,
"lengthChange": false,
"ordering": true,
"processing" : true,
"columns": column_list,
"order": [ [0, 'desc'] ],
"fixedHeader": true,
"orderCellsTop": true,
"ajax": {
url: '/view_datatable/',
type: 'POST'
},
"serverSide" : true, //get data from server
"initComplete": function() { // column filtering RUN after table loaded .
$( '#sample_table tfoot input' ).on( 'keyup change clear', function () {
if ( sample_table.search() !== this.value && this.value.length>0) {
search_result = sample_table.search( this.value );
search_result.draw();
}
} );
}
});
#view.py
def list_datatable(request, companyname):
context = {}
if(request.method == "POST"):
start_page = int(request.POST['start'])
order_direction = request.POST["order[0][dir]"] # direction of ordering(asc, desc)
order_col_no = request.POST["order[0][column]"] # number of index to sort
order_col_name = request.POST['columns[' + str(order_col_no) + '][data]'].strip() # name of colum of ordering
sample_list_all = Sample.objects.all().order_by(order_col_name)
sample_list_per_page = []
for idx, obj in enumerate(sample_list_all[start_page:start_page + 10]):
data = {}
data['id'] = obj.id
data['receiving_at'] = str(obj.receiving_at)
data['birthday'] = obj.birthday
data['serialnumber'] = obj.serialnumber
data['name'] = obj.name
sample_list_per_page.append(data)
#-- end of --#
datalist_to_json = json.dumps(
{"data": sample_list_per_page, "recordsFiltered": len(sample_list_all), "recordsTotal": len(sample_list_all)}
)
return HttpResponse(datalist_to_json, content_type="application/json")

I want a button beneath my datatable to show up if I have only 1 record. How can I pass the ID of the record in table when button is clicked?

Here is the chtml code for the table with my buttons where I want them. I also included the javascript for the table and my .cs controller for the Drawing button. The controller works if I put a button in the table row and pass the record Id on click but I don't want the button in the row. This is because the button intentionally only becomes visible when the datatable is filtered down to one remaining record.
<br />
<div class="container row p-0 m-0">
<div class="col-6">
<h2 class="text-info">Device List</h2>
</div>
<div class="col-12 border p-3">
<table id="DT_load" class="table table-striped table-bordered">
<thead>
<tr>
<th>Drawing File</th>
<th>Barcode</th>
<th>Date Modified</th>
<th>Location</th>
<th></th>
</tr>
</thead>
</table>
</div >
<div class="row" >
<a asp-action="Drawing" class="btn-primary" id="btn1" style="width: 100px" value="0">
View Drawing
</a>
<a asp-action="Location" class="btn-primary" id="btn2" style="width: 100px">
View Location
</a>
</div>
</div>
and here is my javascript
$(document).ready(function () {
loadDataTable();
});
function loadDataTable()
{
dataTable = $('#DT_load').DataTable
({
"ajax":
{
"url": "/devices/getall/",
"type": "GET",
"datatype": "json"
},
"columns":
[
{ "data": "dwgfilename", "width": "20%" },
{ "data": "barcode", "width": "20%" },
{ "data": "moddate", "width": "20%" },
{ "data": "locationdwg", "width": "20%" },
{
"data": "id",
"render": function (data)
{
return `<div class="text-center">
/*ignore*/
</div>`;
}, "width": "60%"
}
],
'infoCallback': function (settings, start, end, max, total, pre)
{
if (total == 1)
{
$("#btn1").show();
$("#btn2").show();
return 'Showing your record';
}
else
{
$("#btn1").hide();
$("#btn2").hide();
return 'Showing ' + total + ' of ' + max + ' records';
}
},
"width": "100%"
});
}
here is the controller for the button
public IActionResult Drawing(int id)
{
//draw
Device = _db.Devices.FirstOrDefault(u => u.Id == id);
if (Device == null)
{
return NotFound();
}
var filename = Device.Dwgfilename;
var stream = new FileStream(#"c:\users\boxworks\documents\" + filename +".pdf", FileMode.Open);
return new FileStreamResult(stream, "application/pdf");
}
Refer to the below working demo and make modification on your javascript:
function loadDataTable() {
dataTable = $('#DT_load').DataTable
({
"ajax":
{
"url": "/home/getall/",
"type": "GET",
"datatype": "json",
"dataSrc":""
},
"columns":
[
{ "data": "orderNumber" },
{ "data": "orderDate" },
{ "data": "description" },
{
"data": "orderId",
"render": function (data) {
return `<lable hidden>`+data+'</lable>';
}, "width": "60%"
}
],
'infoCallback': function (settings, start, end, max, total, pre) {
if (total == 1) {
var id = $("#DT_load tbody tr").find("lable").text();
$("#btn1").attr("href",$("#btn1").attr("href") + "?id=" + id);
$("#btn1").show();
$("#btn2").show();
return 'Showing your record';
}
else {
$("#btn1").hide();
$("#btn2").hide();
return 'Showing ' + total + ' of ' + max + ' records';
}
},
"width": "100%"
});
}
Result:

How to get all checkbox values in cells

I have jQuery datatables with some checkboxes for granting privileges.
I need to get table values to a array. Please enlighten me about how to get checkbox states inside cells, not only the checked ones. Thank you.
My table
<table id="jqueryTable" name="tt" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th name="id">
ID
</th>
<th name="name">
PRIV_Name_Str
</th>
<th name="create">
Create
</th>
<th>
Edit
</th>
<th>
View
</th>
</tr>
</thead>
<table>
My datatable query
function LoadProduct(element) {
$.ajax({
url: '/ADM_MAS_Privilege/GetFormData',
data: { YourValue: $('#productCategory').val() },
method: 'post',
dataType: 'json',
success: function (data) {
var table = $('#jqueryTable').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
bDestroy: true,
"columnDefs":
[{
"targets": [2, 3, 4],
"render": function (data, type, row, meta) {
console.log("XX " + meta.row + " " + meta.col);
return type === 'display' ?
'<input type="checkbox" id="p" class="chk" name="group' + meta.row + '" /> ' + data :
data;
columns: [{ "data": "ID", "ID": "ID", "autoWidth": true },
{
"data": "PRIV_Name_Str", "PRIV_Name_Str": "PRIV_Name_Str", "autoWidth": true
},
{
"data": "Create", "Create": "Create", "autoWidth": true
},
{ "data": "Edit", "Edit": "Edit", "autoWidth": true },
{
"data": "View"
}
]
});
}
});
};
My jQuery function to read datatable
$('#upload').click(function () {
var table = document.getElementById("jqueryTable");
var tableArr = [];
for (var i = 1; i < table.rows.length; i++) {
tableArr.push({
ID: table.rows[i].cells[0].innerHTML,
PRIV_Name_Str: table.rows[i].cells[1].innerHTML,
Create: table.rows[i].cells[2].innerHTML,
Edit: table.rows[i].cells[3].innerHTML,
View: table.rows[i].cells[4].innerHTML
});
}
});
I tried table.rows[i].cells[2].innerHTML.getElementById("p").checked even and it's not working.
Since you are using jQuery:
document.getElementById("jqueryTable").each(function (index, element) {
tableArr.push({
ID: element.cells[0].innerHTML,
PRIV_Name_Str: element.cells[1].innerHTML,
Create: element.cells[2].innerHTML,
Edit: element.cells[3].innerHTML,
View: element.cells[4].innerHTML
})
})
You can find the element and the checked property within each cell:
for (var i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
tableArr.push({
ID: cells[0].innerHTML,
PRIV_Name_Str: cells[1].innerHTML,
Create: cells[2].querySelectorAll('input')[0].checked,
Edit: cells[3].querySelectorAll('input')[0].checked,
View: cells[4].querySelectorAll('input')[0].checked
});
}

dataTable not display ajax data

I need your helps guys. to correct what's wrong with the code.
I want to copy the row table on table1 into table2, but the data does not show up when I use ajax json. have to insert manually into html.
JSFiddle
I want to copy the row table on datatable, but the data does not show up when I use ajax json.
Code Snippet Demonstration
// Code goes here
$(document).ready(function() {
var stockTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // first table
var catalogTable = $('#table2').dataTable(); // Second table
stockTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
catalogTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
$('#LeftMove').on('click',function () {
moveRows(catalogTable, stockTable);
});
$('#RightMove').on('click',function () {
moveRows(stockTable, catalogTable);
});
});
function moveRows(fromTable, toTable){
var $row= fromTable.find(".selected");
$.each($row, function(k, v){
if(this !== null){
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow);
fromTable.fnDeleteRow(this);
}
});
}
/* Styles go here */
#table2_wrapper{
margin-top:50px;
margin-left:50px;
}
#table1_wrapper{
margin-left:50px;
}
table.dataTable tbody tr.selected {
background-color: #b0bed9;
}
table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
background-color: #a6b3cd;
}
table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.display tbody tr.odd:hover.selected > .sorting_1, table.dataTable.display tbody tr.even:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_1 {
background-color: #a1aec7;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css" rel="stylesheet"/>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css" rel="stylesheet"/>
<body>
<div class="one" style="padding-bottom:50px">
<table id="table1" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<center>
<button id="RightMove" style="float:left;">right »</button>
<button id="LeftMove" style="float:left;">« left</button>
</center>
<br>
<br>
<div class="two">
<table id="table2" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
</body>
Edit your ajax call as follows
ajax: {
"url": "https://api.myjson.com/bins/zvujb",
"type": "GET",
"error": function (e) {
},
"dataSrc": function (d) {
return d
}
},
[Problem Solved] https://jsfiddle.net/4fukuma/o6ysgzps/2/
Change jquery file, using jquery-1.12.4.js
and edit table2 js code == table1
$(document).ready(function() {
var stockTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // first table
var catalogTable = $('#table2').dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // Second table
stockTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
catalogTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
$('#LeftMove').on('click',function () {
moveRows(catalogTable, stockTable);
});
$('#RightMove').on('click',function () {
moveRows(stockTable, catalogTable);
});
});
function moveRows(fromTable, toTable){
var $row= fromTable.find(".selected");
$.each($row, function(k, v){
if(this !== null){
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow);
fromTable.fnDeleteRow(this);
}
});
}

How to empty and refill jquery datatable?

I have a jquery datatable on my page. This datatable is gonna show data based on a request made to my api
The HTML that I have is like the following:
<table id="details" class="table table-bordered table-hover table-striped nowrap hidden display" cellspacing="0" width="100%">
<thead>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</tfoot>
<tbody>
<tr id="dummytr2"><td style="text-align:center;padding-top:20px;" colspan="7"><p><em>No Data Available</em></p></td></tr>
</tbody>
</table>
The first <th> is gonna be used to collapse the tr and get the facility (the third <th> or the hidden one) of this patient.
I have a dummy <tr> in the table because I don't want to initialize the datatable at the beginning so I don't get the error message that tells me that I can't initialize my datatable twice.
The request to my api is gonna be triggered through a bunch of buttons like the following:
$.ajax({
url: "https://" + window.myLocalVar + "/api/metrics/GetDetails?metricName=" + metric,
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (requests) {
if (requests.length > 0) {
$("#dummytr2").remove();
for (var i = 0; i < requests.length; i++) {
var patient_name = requests[i].PatientFullName;
var lab_facility = requests[i].LabFacility;
tr = '<tr>\
<td class=" details-control"></td>\
<td>' + patient_name + '</td>\
<td class="hidden">' + lab_facility + '</td>\
</tr>';
$("#details > tbody").append(tr);
//click event for each tr
$('#details tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
}
}
// NOT SURE WHY IT IS NOT WORKING
$('#details').dataTable().fnDestroy();
var table = $('#details').DataTable({
"scrollX": true,
stateSave: true,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "PatientFullName" },
{ "data": "LabFacility" }
],
"order": [[1, 'asc']]
});
},
error: function (err) {
if (err) {
console.log(err);
}
}
});
});
function format(d) {
// `d` is the original data object for the row
var lf = d.LabFacility;
if (lf == "") {
lf = "No Lab Facility"
}
// wrapping text is not working???
return '<div class="table-responsive"><table class="table display" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Lab Facility:</td>' +
'<td>' + lf + '</td>' +
'</tr>' +
'</table></div>';
}
This ajax request is gonna get called each time a button is clicked. This means the content of my datatable is going to change each time a button was clicked. I tried to clear and refill it did not work.. I tried to destroy it .. it did not work.. each time I destroy my datatable and execute the script it won't change the content of the table.
I am not sure what's wrong with my code. My code works only for the first time.. the second time you click a button, it won't update my datatable.
Thanks!
You need to:
empty the table with empty()
remove $('#details').dataTable().fnDestroy();
add destroy: true option
For example:
if (requests.length > 0) {
// Empty table
$('#details').empty();
// ... skipped ...
var table = $('#details').DataTable({
destroy: true,
// ... skipped ...
});
// ... skipped ...
}
Please see sample of what I was saying in comments above:
var dataTable_ = null;
var init_ = false;
var initDataTable = function() {
dataTable_ = $('#table').DataTable({
preDrawCallback: function(settings) {
},
drawCallback: function(settings) {
if (init_ === false) {
init_ = true;
}
},
searching: true,
data: [],
fnCreatedRow: function(nRow, aData, iDataIndex) {
},
scrollY: true,
scrollX: true,
responsive: false,
serverSide: false,
autoWidth: false,
processing: false,
scrollCollapse: false,
lengthChange: false,
fixedColumns: false,
info: false,
select: {
info: false,
items: 'rows'
},
dom: '<"toolbar">Bfrtip',
orderMulti: false,
stripeClasses: ['dt-stripe-1', 'dt-stripe-2'],
columns: [{
name: 'test1',
data: 'test1',
title: 'Test1',
type: 'string',
orderable: true
},
{
name: 'test2',
data: 'test2',
title: 'Test2',
type: 'string',
orderable: true
},
]
});
};
var ajaxFunction = function() {
$.ajax({
url: "https://api.myjson.com/bins/7ed89",
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function(data) {
if (init_ === false) {
initDataTable();
}
if (typeof dataTable_ == 'object') {
dataTable_.rows().remove().draw();
dataTable_.rows.add(data);
dataTable_.draw();
}
//console.log(data);
}
});
};
$('#button').click(function() {
ajaxFunction();
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="table" class="cell-border hover call-list">
</table>
<button id="button">Click To Load Data</button>

Categories

Resources