Why is the table closed? - javascript

Why does the "#reservations" table close when I add the "responsive: true" property? (When you open a child row.) Help me please.
When you click on a row again
enter image description here
function format(d) {
return '<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="records" width="100%">' +
'<thead>' +
'<tr>' +
'<th>Запись</th>' +
'</tr>' +
'</thead>' +
'</table>';
}
(function($){
$(document).ready(function() {
var editor = new $.fn.dataTable.Editor( {
ajax: 'inc/DataTablesEditor/php/table.useruserreservations.php',
table: '#reservations',
fields: [
{
"label": "\u0411\u0440\u043e\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435:",
"name": "reservation"
}
]
} );
var table = $('#reservations').DataTable( {
ajax: 'inc/DataTablesEditor/php/table.useruserreservations.php',
columns: [
{
"data": "reservation",
"class": "details-control"
}
],
select: true,
lengthChange: false,
pageLength: 6,
responsive: true
} );
$('#reservations tbody').on('click', 'td.details-control', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
} else {
if ( table.row( '.shown' ).length ) {
$('.details-control', table.row( '.shown' ).node()).click();
}
var d = row.data();
row.child(format(d)).show();
tr.addClass('shown');
var editor2 = new $.fn.dataTable.Editor( {
ajax: 'inc/DataTablesEditor/php/table.useruserrecords.php',
table: '#records',
fields: [
{
"label": "\u0417\u0430\u043f\u0438\u0441\u044c:",
"name": "record"
}
]
});
var table2 = $('#records').DataTable( {
ajax: {
url: 'inc/DataTablesEditor/php/table.useruserrecords.php',
"type": "POST",
"data": {
"record_reservation": table.row( this ).id().replace(/[^-0-9]/gim,'')
}
},
columns: [
{
"data": "record",
"class": "details-control2"
},
{
"data": "record_user"
}
],
"columnDefs": [
{
"targets": [ 1 ],
"visible": false,
"searchable": false
}
],
select: true,
lengthChange: false,
pageLength: 6,
responsive: true
});
});
} );
}(jQuery));

Related

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);
}
});
}

Data Table Row Undefined(DataTables.js)

I am trying to access the id of a row inside my DataTables application. When I select a particular row, the row gets selected, after that when I hit the edit button on a menu that I have displayed on the website the id of the row should get passed to a url(which I took off because it was not working so I decided to console.log the info)
The problem is that the row id is coming back as undefined even though I can visually inspect that the id is there.
Here is the code:
$(document).ready(function(){
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
columns: [
{"data": "documento"},
{
"data": "fecha_entrada"
},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
],
// add an id for each generated row:
fnCreatedRow: function(nRow, nData, nId) {
$(nRow).attr('id', nData['pk1']);
}
}); // end of datatable creation
$('#example tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#btnEdit').click(function () {
var selectedRow = table.row('.selected').id();
console.log(selectedRow);
});
});
For the selectedRow to show as undefined it must mean that the id is not being added to the datatable, but I know its there:
The id() method does not read the ID from the DOM. Instead of setting the id manually with the fnCreatedRow function use the rowId attribute. This sets the id Attribute in the DOM as well but also stores it internally for the use with the id() method.
So if you change the Datatables initialisation to something like this, your code works:
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
rowId: "pk1",
columns: [
{"data": "documento"},
{"data": "fecha_entrada"},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
]
}); // end of datatable creation
And below a working sample:
var table = $('#sample').DataTable({
serverSide: false,
searching: false,
rowId: "id",
data: [
{ "id": 5, "column-a": "Sample Data A", "column-b": 10, "column-c": "Lore ipsum" },
{ "id": 6, "column-a": "Sample Data B", "column-b": 5, "column-c": "Ipsum" },
{ "id": 8, "column-a": "Sample Data C", "column-b": 38, "column-c": "Lore" }
],
columnDefs: [
{
targets: 0,
data: "id",
title: "id"
},
{
targets: 1,
data: "column-a"
},
{
targets: 2,
data: "column-b"
},
{
targets: 3,
data: "column-c"
}
]
});
$('#sample tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#edit').click(function () {
var selectedRow = table.row('.selected').id();
alert(selectedRow);
});
<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>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<button id="edit">Edit</button>
<table id="sample"></table>

jQuery : How to bind an onClick Event to a DataTable row?

Currently, the dataTable is populated via the server side and everything is working. But I want to add Details|Edit|Delete actionLinks when a row is clicked.
Right now I have them showing in a column at the right side, but I want the links to appear when the user clicks on each row and I cannot workout how to implement it to show onClick.
Can someone please assist me in getting them to show on click? Thank you.
var dt = $('#datatableServer').DataTable({
"serverSide": true,
"ajax":
{
"type": "POST",
"url": "#Url.Action("DataHandler", "Department")"
},
"rowId": 'departmentID',
//"fnRowCallback": function (nRow, aData, iDisplayIndex) {
// nRow.setAttribute('id', aData[0]);
//},
"columns":
[
{
"data": "Name",
"searchable": true
},
{
"data": "Budget",
"searchable": false
},
{
"data": "StartDate",
"searchable": false
},
{
"data": "Administrator",
"searchable": true,
"orderable": false
},
{
// this is the Actions Column I want to show when a Datatable row is clicked, not under a "Action" column
mRender: function (data, type, row) {
var linkEdit = '#Html.ActionLink("Edit", "Edit", new {id= -1 })';
linkEdit = linkEdit.replace("-1", row.DT_RowId);
var linkDetails = '#Html.ActionLink("Details", "Details", new {id= -1 })';
linkDetails = linkDetails.replace("-1", row.DT_RowId);
var linkDelete = '#Html.ActionLink("Delete", "Delete", new {id= -1 })';
linkDelete = linkDelete.replace("-1", row.DT_RowId);
return linkDetails + " | " + linkEdit + " | " + linkDelete;
}
}
],
"order": [0, "asc"],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]]
});
$('#datatableServer tbody').on('click', 'tr', function () {
console.log('clicked');
// get the row Id
console.log(dt.row(this).data().DT_RowId);
});
}); // end of document.ready tag
I made my mRender function a separate function and then called it in the click event function for the datatable body.
function format (data, type, row) {
var linkEdit = '#Html.ActionLink("Edit", "Edit", new {id= -1 })';
linkEdit = linkEdit.replace("-1", row.DT_RowId);
var linkDelete = '#Html.ActionLink("Delete", "Delete", new {id= -1 })';
linkDelete = linkDelete.replace("-1", row.DT_RowId);
return linkEdit + " | " + linkDelete;
}
$('#dtServer tbody').on('click', 'td', function () {
var tr = $(this).closest('tr');
var row = dt.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');
}
});

Column filtering according to type in a loop

I am doing column filtering by using this example as reference and this is what I am doing and it's working fine.
I have multiple columns so how can we implement it by using loop here?
$(document).ready(function() {
var table;
// DataTable
table = $('#example').dataTable({
"processing": true,
stateSave: true,
"deferRender": true, // to make the search fast
"dom": 'C<"clear">Rfltipr', // for column Re-odering and column visibilty.
"ajax": {
"url": "/my/example.so",
"type": "GET"
},
"columns": [{
"title": "name",
"data": "name",
"name": "name"
}, {
"title": "addeddate",
"data": "addeddate",
"name": "added date"
}]
});
table.columnFilter({
sPlaceHolder: "head:before",
aoColumns: [{
type: "text"
}, {
type: "date-range",
bRegex: true,
bSmart: true
}
}
]
});
$.datepicker.regional[""].dateFormat = 'yy-mm-dd';
$.datepicker.setDefaults($.datepicker.regional['']);
Moreover, here I need to write <th> tags also for all columns which is not good in case of multiple columns AS WELL. // second way to do it which is not suitable to do for date column Setup - add a text input to each cell
var noofcolumn= $('#example thead th').length;
colmn="";
for(i=0; i<noofcolumn; i++)
{
var title = $('#example thead th').eq( i ).text();
colmn+='<th><input type="text" placeholder="Search '+title+'" /></th>';
}
$('#example tfoot').html( colmn );
// Apply the search
table.columns().every( function ()
{
$('input', this.footer() ).on( 'keyup change', function () {
table
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
});

Child Row always expanded in datatables.net

i have created parent child row table using datatables.net. On Click of a row the child row is shown. but i want child always open with out any click event on row. Can somebody suggest me how to achieve it
here is my code
var ecumTbl= S$("#EncumbranceSummaryTable").DataTable(
{
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
if(api.column(3).data().length)
{
total = api
.column( 1 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
} );
}
else
{
total =0
};
// Total over this page
if(api.column(3).data().length)
{
pageTotal = api
.column( 3, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column(2).footer() ).html(
'Contract Total'
);
$( api.column(3).footer() ).html(
formatCurrency(pageTotal)
);
}
else{
pageTotal=0;
};
},
"aoColumns": [
{
"sTitle": "", "sWidth": "10%"
},
{ "sTitle": "Sub total for PO #", "mData": "PO_Num", "sWidth": "15%" },
{ "sTitle": "Encumbrance","mData": "Encumbrance", "sWidth": "35%" },
{ "sTitle": "Release","mData": "Release", "sWidth": "45%" },
{ "sTitle": "Paid","mData": "Paid", "sWidth": "45%" },
{ "sTitle": "Balance","mData": "Balance", "sWidth": "45%" },
],
"paging": false,
"ordering": false,
"data": Customers,
"info": false,
"bJQueryUI": true,
'sDom': 't',
"columnDefs": [{
"targets": [0],
"bSearchable": false,
"bSortable": false,
"className": 'details-control',
"mData": null,
"defaultContent": '',
}]
});
//On row click show child table
$('#EncumbranceSummaryTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = ecumTbl.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');
var innerPOTbl= S$("#innerPOTable").DataTable(
{
"bJQueryUI": true,
"aoColumns": [
{ "sTitle": "FY", "mData": "fiscalYrs", "sWidth": "20%" },
{ "sTitle": "Ln","mData": "ln", "sWidth": "15%" },
{ "sTitle": "F/F/A","mData": "ffa", "sWidth": "30%" },
{ "sTitle": "Project ID", "mData": "projectID", "sWidth": "25%" },
{ "sTitle": "Source Type","mData": "sourceType", "sWidth": "30%" },
{ "sTitle": "Encumbrance","mData": "encumbrance", "sWidth": "35%" },
{ "sTitle": "Released","mData": "released", "sWidth": "35%" },
{ "sTitle": "Paid","mData": "paid", "sWidth": "35%" },
{ "sTitle": "Balance","mData": "balance", "sWidth": "35%" },
],
"sDom": 'lfrtip',
"data":PurchaseOrderList,
"paging": false,
"ordering": false,
"info": false,
"bJQueryUI": false,
});
}
});
Another solution using DataTables "draw" event. I find this solution more comfortable as it is part of the Datatables object and placed in the "draw" event ensures it fires only after the table has been fully initialized and then on performed on each draw event.
var table = $('#sample')
.DataTable({
// your table configuration...
})
.on('draw.dt', function () {
table.rows().every(function () {
this.child(format(this.data())).show();
this.nodes().to$().addClass('shown');
// this next line removes the padding from the TD in the child row
// In my case this gives a more uniform appearance of the data
this.child().find('td:first-of-type').addClass('child-container')
});
});
// this is my format function for the child data
// do as you need for your case
function format(d) {
// `d` is the original data object for the row
return '<table class="row-detail">' +
'<tr>' +
'<td title="State">' + d.rState + '</td>' +
'<td title="Comment">' + d.rComment + '</td>' +
'<td title="Category">' + d.rCategory + '</td>' +
'</tr>' +
'</table>';
}
And here is the style class for the child TD and its table.
<style>
.child-container{
padding: 0 !important;
}
table.row-detail {
border-collapse: collapse;
width: 100%;
}
table.row-detail td {
padding: 5px 10px !important;
border-right: 1px solid #ddd;
}
</style>
SOLUTION
Add this code to show all child rows:
$("#EncumbranceSummaryTable").DataTable().rows().every( function () {
this.child(format(this.data())).show();
this.nodes().to$().addClass('shown');
// Child table initialization
var innerPOTbl = $(".child-table", this.nodes().to$()).DataTable(
// ... skipped
);
} );
See row().child() for more information.
DEMO
/* 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');
}
} );
// Show all child nodes
$("#example").DataTable().rows().every( function () {
this.child(format(this.data())).show();
this.nodes().to$().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>

Categories

Resources