Recently, I got a requirement for an implementation of adding Child rows in a table. I have gone through the few APIs and found that datatables fits into my requirement. As of now I am implementing this web application in Springs and getting the data from the controller.
That is $resultSet.
Now this dynamic data I have to render in jsp page. Here I got stucked because I am not able to implement with datatable. I have seen the example of http://datatables.net/examples/api/row_details.html and tried removing Ajax data and used c:foreach loop in place it. But i didn't get any luck.
So can you guys please tell me how do I use datatables with the dyncamic data in order to display child rows.
My main concern is:
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
How do I represent the above block.
I tried with <table id="xx"> <c:foreach loop to iterate>
You can use data option to feed data into DataTables directly instead of using server-side script to return data via Ajax. This initialization option can be useful when creating a table from a JavaScript data source, or from a custom Ajax data get. However the data has to be of type Array.
I'm not familiar with Spring framework but I'm assuming you can produce a string with data in JSON format and output it in your page to assign to table_data_json. I'm using a sample JSON string var table_data_json = '[ /* skipped */ ]';.
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table_data_json = '[{"name":"Tiger Nixon","position":"System Architect","salary":"$320,800","start_date":"2011/04/25","office":"Edinburgh","extn":"5421"},{"name":"Garrett Winters","position":"Accountant","salary":"$170,750","start_date":"2011/07/25","office":"Tokyo","extn":"8422"},{"name":"Ashton Cox","position":"Junior Technical Author","salary":"$86,000","start_date":"2009/01/12","office":"San Francisco","extn":"1562"}]';
var table = $('#example').DataTable( {
"data": JSON.parse(table_data_json),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example 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');
}
} );
} );
td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<table id="example" class="display">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
If I misunderstood your question, please let me know and I will update my answer.
Related
everything works fine. The only issue that i cannot fix/find is how to create a button and set the value of data: cvpdf inside a href of a button to open the cv
The cvpdf is the file name of a cv stored in the database.
<table id="dtBasicExample" class="table table-striped custom-table mb-0 datatable " >
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>email</th>
<th>position</th>
<th>CV</th>
</tr>
</thead>
<tbody id="atn-tbody">
</tbody>
</table>
function showInformation(str) {
console.log(str);
$("#dtBasicExample").dataTable().fnDestroy();
$(document).ready(function(){
$("#dtBasicExample").dataTable({
scrollX: true,
"ajax":{
url: "data.php?q="+str ,
dataSrc:"",
},
"columns":[
{"data": "id"},
{"data": "name"},
{"data": "surname"},
{"data": "email"},
{"data": "position"},
{"data": "cvpdf"},
]
});
});
};
Let me help you out with this. you can apply this to any column data
columns: [
{
data: function(row){
return `Click This`
}
}
]
the "row" parameter will return the whole data for the current row, so you can access the object through the "row.your_key".
this is the best practice to make your code simpler.
the complete parameter can be accessed through This Link
Hope it can help!
My target is to have an individual filtering for column. My reference is: https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html
The problem I am encountering right now when I type, my datatable doesn't do any filtering and it shows an error regarding CURSORPOSITION:
I followed the guide thoroughly and made a lots of research but I still failed to achieve my goal. I hope you can help me
Views:
<table id="example" class="table table-bordered table-hover table-striped is-narrow is-hoverable is-fullwidth text-nowrap" style="width: 100%;">
<thead>
<tr>
<th>TESTING ID</th>
<th>TESTING ACTION</th>
<th>TESTING DESC</th>
<th>TESTING Date</th>
<th>TESTING VENUE</th>
<th>TESTING TICKET</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
$(document).ready(function() {
$('#example thead tr')
.clone(true)
.addClass('filters')
.appendTo('#example thead');
table = $('#example').DataTable({
dom: 'lfrtip',
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$(
'input',
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
});
},
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/lists')?>",
"type": "POST",
async:true,
dataType: "json",
"data": function(data){
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
How to put a 'if' query on Ignited datatable? Here is my query:
This is my controller:
function ajaxGetCard() {
$this->load->library('Datatables');
$this->datatables->set_database('retail');
$this->datatables
->select('studEmpID, fullname, serialNumber, balance, If(status = "0", "Enable", "Disabled") as status')
->from('retail_card');
echo $this->datatables->generate();
}
This is my view:
<script type="text/javascript">
$(function() {
$('#example').DataTable( {
"bProcessing": true,
"bserverSide": true,
"ajax": "<?php echo site_url('card/ajaxGetCard'); ?>",
"columns": [
{ "data": "studEmpID" },
{ "data": "fullname" },
{ "data": "serialNumber" },
{ "data": "balance" },
{ "data": "status" },
{ "data": "actions" }
]
} );
});
</script>
<table class="table table-bordered datatable table-striped" id="example">
<thead>
<tr>
<th>ID Number</th>
<th width="30%">Name</th>
<th>Serial</th>
<th>Balance (MYR)</th>
<th>Status</th>
<td>Actions</td>
</tr>
</thead>
When I run this, I've got this error:
DataTables warning: table id=example - Ajax error. For more information about this error, please see http://datatables.net/tn/7
I already refer the given url, but still not solve the problem. If I remove the the 'if' statement in that query, everything works fine. Please help
I have got a datatable using Datatables server-side. I have created and filled the table as shown below. Now I need to translate the datatable depending on the language , I found this example in the documentation :
$('#example').DataTable( {
language: {
search: "Search in table:"
}
} );
or loading translation :
$('#example').DataTable( {
language: {
url: '/localisation/fr_FR.json'
}
} );
But none of them works for me ! this is my code :
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "server-side-process",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
var oTable = $('#example').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"processing": true,
"serverSide": true,
"ajax": {...
https://datatables.net/plug-ins/i18n/
Below is a working example of two datatables. One using default English and one loading French as per the documentation: https://datatables.net/reference/option/language
JSFiddle link: https://jsfiddle.net/invalidname/mro9h48u/2/
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
$(document).ready(function() {
var oTable = $('#exampleFR').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/French.json"
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<H1>
English table
</H1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
<hr>
<hr>
<H1>
French table
</H1>
<table id="exampleFR" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
I am using Ajax Datatable, I want to feed the table with Json data, which i am returning from MVC Action method. This is what i have tried so far,
My Controller action method
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees select new { e.FirstName, e.LastName, e.Username, e.Password }).ToList();
return Json(query,JsonRequestBehavior.AllowGet);
}
And here is my Javascript on Index page
</script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "Home/Index",
"dataType": "jsonp"
}
});
});
</script>
But on page load only the plain Json data can be seen and no data table, I think It is not even rendering the Html on the index page and hence neither Datatable as I can not see anything in chrome debugger.
Also, Html and script referencing is all Ok as I can see the results when I feed the datatable from a .txt file having array of data.
I don't know what is the right way to do that, If somebody has the solution for that, then please help, Thanks.
I think what you need to do is simply the following
</script>
$(document).ready(function () {
$('#example').dataTable({
"ajax": "/Home/Index",
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Username" },
{ "data": "Password" },
]
});
});
</script>
No need for the processing and serverside and they are used when you have large data and would like to have paging and sorting done on the server side which is not the case in your code
One possible way is to define your "regular" table markup in a razor view/partial/ view - id your table, ie, id="DataTables-Employee". Your controller code looks just fine but with an ActionResult return a View with the model data. This let you control the data by using razor syntax in your view, which I have found much easier than complex JSON results. (Also, I like to use AutoMapper to project my model data to - give it a try!)
Note: this is only one of several ways to do this. Server-side processing helps when working with huge datasets, but give the client-side a try. I use ajax but flatten your model result. More likely than not you will need to define your columns and map them to your JSON. If you want to post your table results, add a form tag. I use ajax for this and serialize my form before sending. I hope this helps!
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees
select new {e.FirstName, e.LastName, e.Username, e.Password};
//I would recommend using AutoMapper and project your model to this
return View(query.ToArray());
}
Say you are working with an Index view:
#model dynamic
... //typical HTML table
<table class="display compact table table-striped table-hover dataTables_sizing table-condensed" id="dataTables-Employee">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>User Name</th>
<th class="no-sort">Actions</th>
</tr>
</thead>
#foreach (var emp in Model)
{
<tr>
<td>#emp.FirstName</td>
<td>#emp.LastName</td>
<td>#UserName</td>
<td style="width: 100px;">
<i class="fa fa-search"></i>
#Ajax.ActionLink("View", "Index", new { id = #app.EmployeeId },
new AjaxOptions
{
dateTargetId = "resultSection",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace
})
</td>
</tr>
}
</table>
//Know make it a DataTable
$('#dataTables-Employee').DataTable({
scrollY: '330px',
scrollCollapse: true,
paging: true,
scrollX: false,
"columnDefs": [{
"orderable": false,
"targets": 2
}, {
className: "dt-center",
"targets": [3]
}],
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"options": {
"emptyTable": "No records to display..."
}
});
Example of results with Bootstrap styles: