need help with editable tables in jQuery ( DataTables plugin ) - javascript

I'm trying to use jQuery and its plugin DataTables ( http://www.datatables.net/release-datatables/examples/api/editable.html ), to make an editable table.
Here's my code so far. The top part of it works great by generating a table inside a DIV with the data from a js array.
Yet I also need this table to be editable. I have found an example code for it ( see bottom part ) but kinda can't figure out how to apply it to my table?
Any ideas? Thanks!
$(document).ready(function() {
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
/// create a table within the '#dynamic' DIV
$('#example').dataTable( {
"aaData": numbarr, /////// takes data from the 'numbarr' js array.
"aoColumns": [
{ "sTitle": "Country " }, //// column names
{ "sTitle": "Number " },
{ "sTitle": "Tariff ID " },
{ "sTitle": "Customer Acc " },
{ "sTitle": "Customer Name " },
{ "sTitle": "Payment Terms " },
{ "sTitle": "Payout/Call " },
{ "sTitle": "Payout/Min " },
]
} );
///////////////////////////// the code above workd fine!
////////////////// this code was taken from an example, not sure how to connect it with my table...
$('td', oTable.fnGetNodes()).editable( '../examples_support/editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "12px"
} );
////////////////// this code was taken from an example, not sure how to connect it with my table...

I've used this plugin http://square-bracket.com/openjs

The example I see states to initialize your table like:
$('#example').dataTable(options).makeEditable(options);
That being said, I haven't gotten it to work yet either.

This is an example that works for me:
$('#tblDataTable2').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aaSorting": [[ 0, "asc" ]],
"aoColumnDefs": [
{ "sClass": "center", "aTargets": [ 0, 1 ] }
]
}).makeEditable({
sAddURL: "Setting?operation=create",
sUpdateURL: "Setting?operation=update",
"aoColumns": [
{ placeholder: '' },
{ placeholder: '' }
],
});

Related

How to pass values of a column of rows whose checkboxes are selected in jQuery Data Table

I have a datatable which is getting populated by an ajax call. Following is the code:
oTable = $('#lenderList').dataTable(
{
bServerSide: true,
bProcessing: true,
searching: true,
sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
sServerMethod: 'POST',
sPaginationType: "full_numbers",
columnDefs:[
{
targets:8,
checkboxes:{
selectrow:true
}
}
],
aoColumns: [
{
"sName": "loanApplicationNumber",
mData: "loanApplicationNumber"
},
{
"sName": "name",
mData: "name"
},
{
"sName": "submissionDate",
mData: "submissionDate"
},
{
"sName": "kycEmailId",
mData: "kycEmailId"
},
{
"sName": "appVersion",
mData: "appVersion"
},
{
"sName": "documentStatus",
mData: "documentStatus"
},
{
"sName": "latestRemark",
mData: "latestRemark"
},
{
"sName": "appName",
mData: "appName"
},
{
nData: "salaryTransaction",
render: function ( salaryTransaction, type, row ) {
if ( type === 'display' ) {
return '<input type="checkbox" class="editor-active">';
}
return salaryTransaction;
},
className: "dt-body-center"
}
],
dom: '<"button">lfrtip'
}
);
});
I have to consider all the loan application numbers of the respective rows whose checkboxes are checked by the user. So I can trigger an event on Click of a button but how can I get the values of Loan Application Number of those rows whose checkboxes are clicked.
I am new to javaScript. Please let me know how this can be achieved.
I have this idea : Loop through all the rows of the table, and test if the checkbox of that row is checked or not. If it is, then extract the value of the needed cell!
Try this :
$(document).ready(function(){
$("button").click(function(){
oTable = $("#lenderList").dataTable(); // Get the datatable,
var loanApplicationNumbers = []; // An array that will contain the "loan application numbers"
oTable.$('tr').each(function(index,rowhtml){ //Loop through the table rows
//Check the state of the checkbox
var checked= $('input[type="checkbox"]:checked',rowhtml).length;
if (checked==1){
//If the checkbox is checked, then add the inner text of the cell to the array
loanApplicationNumbers.push(rowhtml.children[1].innerText);
}
});
console.log(loanApplicationNumbers); //Do whatever you want
});
});
Note : rowhtml.children is an Array of cells in that row, if you want to get the value of the first cell, you should do rowhtml.children[0].innerText .

DataTable - Column 1 cells ( use values from array ), column 2 cells ( use custom html)

I want to create a datatable wherein my first column values come from an array and second and other columns contains custom html ( select boxes, inputs etc).I have used datatable before but that time i was reading data from json ( for all columns ) like this:
function basketTable(data){
topTable = $('#at-top-100').dataTable({
//layout of data table
"dom": 'Tlfrtip',
"bInfo" : false,
"bDestroy":true,
"bFilter" : false,
"responsive":true,
"aaData" : data,
"aoColumns": [
{ "mData": "Ap" },
{ "mData": "Dp" },
{ "mData": "A"},
{ "mData": "S"},
{ "mData": "S"},
],
"iDisplayLength": 10,
"oLanguage": {
"sSearch": "",
"sSearchPlaceholder" : "Search..",
"sLengthMenu": " _MENU_ ",
}
});
}
Any insight on how i can achieve this. Any help would be greatly appreciated!!
Use the "mrender" function and place any html you want to render per cell in the function.
You can also access the properties of the object in the row if you want to use them in your display.
http://legacy.datatables.net/usage/columns
function basketTable(data){
topTable = $('#at-top-100').dataTable({
//layout of data table
"dom": 'Tlfrtip',
"bInfo" : false,
"bDestroy":true,
"bFilter" : false,
"responsive":true,
"aaData" : data,
"aoColumns": [
{ "mData": "Ap" },
{ "mData": "Dp" },
{ "mData": "A"},
{ "mData": "S"},
{ "mData": "S",
"mRender": function(data,type,full)
{
return '<input type="text" value="Scanners and Scales"/>'
}
],
"iDisplayLength": 10,
"oLanguage": {
"sSearch": "",
"sSearchPlaceholder" : "Search..",
"sLengthMenu": " _MENU_ ",
}
});
}

Datatable FixedHeader Plugin Error

i am using Datatable FixedHeader Plugin. check my code. but plugin not work properly.
console error occured "TypeError: $.fn.dataTable.FixedColumns is not a constructor"
please give me solution. thanks
$(document).ready(function() {
var table=$("#example").dataTable( {
"bProcessing": false,
"bServerSide": false,
"sort": "position",
"scrollY":"300px",
"scrollX":"200px",
"scrollCollapse": true,
"sAjaxSource": "searchatOrganisations",
"aoColumns": [
{ "mData": "aoId" },
{ "mData": "aoCreatedby" },
{ "mData": "aoCreatedon" },
{ "mData": "aoModifiedby" },
{ "mData": "aoModifiedon" },
{ "mData": "aoName" },
{
"mData": null,
className: "center",
defaultContent: 'Edit / Delete'
}
]
} );
new $.fn.dataTable.FixedColumns( table, {
leftColumns: 1,
rightColumns: 1
} );
} );
TypeError: $.fn.dataTable.FixedColumns is not a constructor
Include Following JS and CSS to get fixed header in DataTable.
https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.dataTables.min.css
https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js
ref Link: https://datatables.net/download/release
You need to include JS file on your page.
dataTables.fixedHeader.js
I also faced same problem, this is the js which needs to include

Row Grouping in datatables not working

I have been trying to follow this approach of row grouping described in the following link. http://www.datatables.net/examples/advanced_init/row_grouping.html
However while implementing the drawCallback function I had to change the name to "fnDrawCallback" for my datatable to recognize this function and also declare var api as var api = this.oApi._fnGetTrNodes( settings ); instead of the way described in the example (var api = this.api();) as otherwise I was getting an error. However now I am still getting a similar error while defining the rest of function if I follow the syntax and keywords given in the example. That is ,
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="5">'+group+'</td></tr>'
);
The error I get is "undefined is not a function " for the drawCallback function. I tried a lot trying to find a different way of writing the same function but I cannot understand why this doesn't work and why I had to change the api declaration too.
I am very new to this , so if someone could explain what the correct format would be to write this function without this error I would really appreciate it !
Please find my Jquery part listed below. Thanks in advance !!
$(document).ready(function(){
var oTable = $("#tableTenants").dataTable({
"bProcessing": true,
"sAjaxSource": "/api/alltenantstatistic.json?iDisplayStart=0&iDisplayLength=${totalCount}&sSortDir_0=asc",
"aoColumns": [
{ "mDataProp": "state","sClass": "student_rows" , "sWidth":"1%" },
{ "mDataProp": "name","sClass": "student_rows" , "sWidth":"20%"},
{ "mDataProp": "testAdmin","sClass": "student_rows" , "sWidth":"70%"},
{ "mDataProp": "totalStudentCount","sClass": "select_rows" , "sWidth":"2%", "bSortable": false },
{ "mDataProp": "totalPnPStudentCount","sClass": "select_rows" , "sWidth":"2%", "bSortable": false }
],
"aoColumnDefs": [
{ "fnRender": function(oObj) {
return '' + oObj.aData.state + '';
},
"bUseRendered": false,
"aTargets": [0]
},
{
"aTargets": [1],
"bVisible": false
},
],
"iDisplayLength": 10,
"order": [[ 1, 'asc' ]],
"fnDrawCallback": function ( settings ) {
console.log("hello");
var api = this.oApi._fnGetTrNodes( settings ); // Had to change this from this.api();
var rows = api.rows({page:'current'}).nodes(); // Giving an error
var last=null;
api.column(1, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="4">'+group+'</td></tr>'
);
last = group;
}
} );
},
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
//"bStateSave": true,
"sDom": "<'row-fluid'<'span5'l><'span7'f><'span2'>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_",
"sEmptyTable": "No Organization Uploads available for this Tenant",
"sInfoEmpty": "",
"sProcessing": "Loading..."
}
});
Its due to jquery datatable version problem. use below libraries and code
<script src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script src="//datatables.net/release-datatables/extensions/ColReorder/js/dataTables.colReorder.js"></script>
"drawCallback": function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="3">' + group + '</td></tr>'
);
last = group;
}
});
},

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources