jquery datable add checkbox for object initialised table - javascript

I am trying to get a checkbox column added to the jQuery datable, however am unable to do so.
My data table is initialised with a JSON object data and I want to add a column of checkboxes before the data. The data table shows the data but not check box column. The relevant code is as follows
HTML
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
</table>
JAVASCRIPT CODE
msg = $.parseJSON(msg);
console.log(msg);
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": null,
"defaultContent": "<button>Click!</button>"
}]
});
PHP CODE TO GET DATA FROM MYSQL DATABASE
$result = $conn->query($sql);
//$result = $result->num_rows;
if($result->num_rows >0){
$res = array();
while($row =mysqli_fetch_assoc($result))
{
$res[] = $row;
}
//$res = array( "data"=>$res);
$output = json_encode($res);
} else
{
$output = 'fail';
}
echo $output;
die();
I have searched through the forums but all of the results i get are for ajax sourced data and not ones populated like I do.
Regards,

You can try this:
HTML
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" name= "check_all" id="check_all" value="1" /></th>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
Javascript:
msg = $.parseJSON(msg);
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": "RequestID",
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" name= "check_id[]" data-id="'+data+'" />';
},
}]
});

Related

load json data in bootstrap data table

i created a table using html . now i want to populate my table using json data. i have been using the example https://www.youtube.com/watch?v=A20PY5RxdI8
my javascript code is here
$(document).ready(function () {
$.getJSON("my.php", function(json){
myjson = json;
}).done(function() {
$('#tble').bootstrapTable('load', myjson);
var $table = $('#tble');
$table.bootstrapTable('load', myjson);
$table.bootstrapTable({
search: true,
pagination: true,
buttonsClass: 'primaryt',
showFooter: true,
minimumCountColumns: 2,
columns: [ {
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}],
data: myjson
});
});
});
<table id = 'tble'>
<tr class=xl70 height=42 style='mso-height-source:userset;height:31.5pt'>
<th height=42 class=xl72 width=57 style='height:31.5pt;border-top:none;
border-left:none;width:43pt' data-field="one">1</th>
<th class=xl72 width=80 style='border-top:none;border-left:none;width:60pt'>2</th>
<th class=xl72 width=97 style='border-top:none;border-left:none;width:73pt'>3</th>
</tr>
</table>
i want to populate json into my table but it does not display any data in the said table
You can use the following code example:
$.getJSON("my.php")
.done(function(data) {
$('#tble').bootstrapTable('load', data);
})
Read the $.getJson() documentation for more example.
I have checked the documentation of Bootstrap table which you are using in your example.
The document is poorly written without explaining the parameters. Which results in confusion. When you read the document and do some JS fiddle you will realise that data-toggle attribute is very important. The value of this attribute should be the same as the Id of your table.
you can try removing data attribute filed in below fiddle to verify it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.js"></script>
<div id="toolbar">
<button id="button" class="btn btn-secondary">load</button>
</div>
<table
id="table"
data-toggle="table"
data-height="460">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
</table>
<script>
var $table = $('#table')
var $button = $('#button')
function randomData() {
var startId = ~~(Math.random() * 100)
var rows = []
for (var i = 0; i < 10; i++) {
rows.push({
id: startId + i,
name: 'test' + (startId + i),
price: '$' + (startId + i)
})
}
return rows
}
$(function() {
var someData = randomData();
debugger;
$table.bootstrapTable('load', someData)
})
</script>
You will need to modify your code as below.
HTML
<table id = 'tble' data-toggle="tble">
<thead>
<tr>
<th data-field="one">ID</th>
<th data-field="two">f name</th>
<th data-field="three">last name</th>
</tr>
</thead>
</table>
and JS
$(document).ready(function () {
$('#table').bootstrapTable({
url: 'my.php',
pagination: true,
search: true,
columns: [{
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}]
})
});
Note: your URL should return a json response. Else instead of getJSON you can use $.ajax

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

Best Practice to Lazy Load Huge Data into a Table

I have a fiddle that make an AJAX to get this Data to render a table. My goal is load only 10 rows during the first initial page load.
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Account ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
JavaScript
$(document).ready(function() {
$('#example').DataTable( {
"bPaginate": true,
"processing": true,
"bServerSide": true,
ajax: {
url: 'https://api.myjson.com/bins/1egsx',
dataSrc: 'data'
},
columns: [
{ data: 'account_id' },
{ data: 'name' },
{ data: 'email' }
],
"deferRender": true,
"deferLoading": 10,
} );
});
I've been trying to use datatables JavaScript plug-in, but it doesn't seem to work.
Are there any other scripts/plug-ins/frameworks I should look into?

DataTable ajax Nested Table with search

I have created jQuery DataTable with ajax which is working fine but I need to add another nested table inside it and it should be search from parent table. Is it possible !!
HTML
<table id="gatePass" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Company Name</th>
<th>From Date</th>
<th>To Date</th>
<th>Area</th>
<th>Status</th>
<!--<th style="display:none">itemId</th>-->
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript
var dataTableExample = 'undefined';
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
var a = "/_api/lists/getbytitle('GatePass')/items?$select=Id,Title,FromDate,ToDate,Area,OtherOldBuildingArea,OtherNewBuildingArea,WFStatus&$filter=WFStatus eq 'Approved'";
$.ajax({
url: a,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample = $("#gatePass").DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ mData: "Title" },
{
mData: "FromDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{
mData: "ToDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{ mData: "Area" },
{ mData: "WFStatus" },
]
});
}
function myErrHandler(data, errCode, errMessage) {
alert("Error: " + errMessage);
}
What is good for nested table to get data directly from ajax or to make dynamic string and to the table. Issue is if I make dynamic string than I think I cannot search on it. Please help me.

Unable to display data using jQuery datatables, AJAX and JSON

I'm having a problem displaying my data on my jQuery DataTable using AJAX. I'm using the library from datatables.net. I've tried packaging the JSON in many different formats and nothing is working. I've also messed around with the 'columns' section, interchanging 'title' and 'data.' I only have one event to display for now, but the bottom of the table shows something crazy like 4,000 entries. Here is my code:
<script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/api/EventsApi/GetAll",
"dataSrc": ""
},
columns: [
{ title: "Title" },
{ title: "Template" },
{ title: "Capacity" },
{ title: "Boarding Location" },
{ title: "Status" },
{ title: "Edit / Delete" }
//{ "data": "title" },
//{ "data": "eventTemplateID" },
//{ "data": "locomotive.capacity" },
//{ "data": "boardingLocationStart.city" },
//{ "data": "status" },
//{ "data": "status" }
]
});
});
<div class="title-content">#ViewBag.Title</div>
<div id="dataTable">
<table id="myTable" class="table table-hover" style="text-align: center;">
<tbody id="tBody">
<!-- Table body data goes here -->
</tbody>
</table>
</div>
Here is the JSON that's being returned from the AJAX call:
{"data":[{"tripEventID":1,"extraDetails":"this train has special details","eventName":"ZombieTrainEventName ","departureDate":"\/Date(1443715200000)\/","returnDate":"\/Date(1443718800000)\/","eventCapacityOveride":100,"eventTemplateID":3,"title":"The Zombie Train ","companyID":1,"description":"description of zombie train ride ","boardingClosed":30,"status":1,"boardingLocationStart":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationStartTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnFrom":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"allowFlexableReturnDate":false,"product":[],"productBundle":[{"bundleID":10,"companyID":1,"displayName":" Pumkin Bundle copy Test","price":0.0100,"tax":0.0200,"productList":[]}],"locomotive":{"trainID":1,"companyID":1,"title":"Skunk_Steam ","type":1,"description":"Steam locomotive ","capacity":998,"status":0},"media":{"mediaID":1,"companyID":1,"hero":[],"gallery":[{"mediaDetailID":6,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":null,"url":null},{"mediaDetailID":7,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":"path6","url":"url6"},{"mediaDetailID":8,"formatTypeID":2,"fileName":"testimage7.txt","order":1,"path":"path7","url":"url7"}],"inside":[{"mediaDetailID":1,"formatTypeID":1,"fileName":"testimage.txt","order":1,"path":null,"url":null},{"mediaDetailID":2,"formatTypeID":1,"fileName":"testimage2.txt","order":1,"path":null,"url":null},{"mediaDetailID":3,"formatTypeID":1,"fileName":"testimage3.txt","order":1,"path":null,"url":null}]},"duration":15,"isExclusive":false,"timeAtDestination":45,"isOneWay":false}]}
Like I said, I've tried repackaging the JSON as nested objects and arrays with nothing working. Am I missing something obvious? Any help is appreciated, thank you!
You have to name the columns in your js like the json index keys like this:
$(document).ready(function() {
$('#myTable').DataTable( {
"ajax": "path/to/your/file.json",
"columns": [
{ "data": "title" },
{ "data": "eventTemplateID" },
{ "data": "eventCapacityOveride" },
{ "data": "boardingLocationStart.streetAddress" },
{ "data": "status" },
{ "data": null }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
Note that you can define custom data in tables with the columnDefs option.
And than edit your HTML with something like this:
<table id="myTable" class="table table-hover" style="text-align: center;">
<thead>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</tfoot>
</table>
Here you can find a working fiddle

Categories

Resources