How to implement nested datatables with unlimited depth? - javascript

I need datatables that can have nested rows dynamically created based on the data.
Something like this but with unlimited nested rows:
https://jsfiddle.net/dyv4L8bp/4/
Here is the code I have tried so far (taken from an example I found):
function fnFormatDetails(table_id, html) {
var sOut = "<table id=\"exampleTable_" + table_id + "\">";
sOut += html;
sOut += "</table>";
return sOut;
}
//////////////////////////////////////////////////////////// EXTERNAL DATA - Array of Objects
var terranImage = "https://i.imgur.com/HhCfFSb.jpg";
var jaedongImage = "https://i.imgur.com/s3OMQ09.png";
var grubbyImage = "https://i.imgur.com/wnEiUxt.png";
var stephanoImage = "https://i.imgur.com/vYJHVSQ.jpg";
var scarlettImage = "https://i.imgur.com/zKamh3P.jpg";
// DETAILS ROW A
var detailsRowAPlayer1 = { pic: jaedongImage, name: "Jaedong", team: "evil geniuses", server: "NA" };
var detailsRowAPlayer2 = { pic: scarlettImage, name: "Scarlett", team: "acer", server: "Europe" };
var detailsRowAPlayer3 = { pic: stephanoImage, name: "Stephano", team: "evil geniuses", server: "Europe" };
var detailsRowA = [ detailsRowAPlayer1, detailsRowAPlayer2, detailsRowAPlayer3 ];
// DETAILS ROW B
var detailsRowBPlayer1 = { pic: grubbyImage, name: "Grubby", team: "independent", server: "Europe" };
var detailsRowB = [ detailsRowBPlayer1 ];
// DETAILS ROW C
var detailsRowCPlayer1 = [{ pic: terranImage, name: "Bomber", team: "independent", server: "NA" }];
var rowA = { race: "Zerg", year: "2014", total: "3", details: detailsRowA};
var rowB = { race: "Protoss", year: "2014", total: "1", details: detailsRowB};
var rowC = { race: "Terran", year: "2014", total: "1", details: detailsRowCPlayer1};
var newRowData = [rowA, rowB, rowC] ;
////////////////////////////////////////////////////////////
var iTableCounter = 1;
var oTable;
var oInnerTable;
var detailsTableHtml;
//Run On HTML Build
$(document).ready(function () {
// you would probably be using templates here
detailsTableHtml = $("#detailsTable").html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
nCloneTd.innerHTML = '<img src="http://i.imgur.com/SD7Dz.png">';
nCloneTd.className = "center";
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
$('#exampleTable tbody tr').each(function () {
this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
"bJQueryUI": true,
"aaData": newRowData,
"bPaginate": false,
"aoColumns": [
{
"mDataProp": null,
"sClass": "control center",
"sDefaultContent": '<img src="http://i.imgur.com/SD7Dz.png">'
},
{ "mDataProp": "race" },
{ "mDataProp": "year" },
{ "mDataProp": "total" }
],
"oLanguage": {
"sInfo": "_TOTAL_ entries"
},
"aaSorting": [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody td img').live('click', function () {
var nTr = $(this).parents('tr')[0];
var nTds = this;
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
var rowIndex = oTable.fnGetPosition( $(nTds).closest('tr')[0] );
var detailsRowData = newRowData[rowIndex].details;
this.src = "http://i.imgur.com/d4ICC.png";
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, detailsTableHtml), 'details');
oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
"bJQueryUI": true,
"bFilter": false,
"aaData": detailsRowData,
"bSort" : true, // disables sorting
"aoColumns": [
{ "mDataProp": "pic" },
{ "mDataProp": "name" },
{ "mDataProp": "team" },
{ "mDataProp": "server" }
],
"bPaginate": false,
"oLanguage": {
"sInfo": "_TOTAL_ entries"
},
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var imgLink = aData['pic'];
var imgTag = '<img width="100px" src="' + imgLink + '"/>';
$('td:eq(0)', nRow).html(imgTag);
return nRow;
}
});
iTableCounter = iTableCounter + 1;
}
});
});
Can someone send me an example. Please dont send examples with a single nested row only. I need unlimited ones.

Related

Dynamically deleting elements Jquery

I have a js file that is supposed to create a list of things with a delete button
The list gets created, and the first time that an element is deleted, it works fine. However, when I click on the delete button the second time, nothing happens. Why is this?
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$(".delete-button").click(function() {
names = Number(this.id)
sales.splice(names, 1)
makeEntries(sales)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>
You need an updated index of the Object in Array.
The simplest way to achieve it is: sales.splice(sales.indexOf(item), 1);
Don't rebuild your entire elements again and again. Just remove that single one both from DOM and Array.
Regarding your code, here's a better way to code it using jQuery:
const sales = [{
salesperson: "James D. Halpert",
client: "Shake Shack",
reams: 100,
}, {
salesperson: "Stanley Hudson",
client: "Toast",
reams: 400,
}, {
salesperson: "Michael G. Scott",
client: "Computer Science Department",
reams: 1000,
}];
const $main = $("#main");
const makeEntries = (sales) => {
const outers = sales.map(item => {
const $outer = $("<div>", {class:"outer"});
const $person = $("<div>", {text: item.salesperson, class: "start", appendTo: $outer});
const $client = $("<div>", {text: item.client, class: "mid-1", appendTo: $outer});
const $reams = $("<div>", {text: item.reams, class: "mid-2", appendTo: $outer});
const $delete = $("<button>", {
text: "Delete",
class: "delete-button",
appendTo: $outer,
on: {
click() {
sales.splice(sales.indexOf(item), 1);
$outer.remove();
console.log(sales);
}
}
});
return $outer;
});
$main.empty().append(outers);
};
jQuery($ => {
makeEntries(sales);
});
#main { display: flex; }
.outer {flex: 1; padding: 10px; border: 1px solid #aaa;}
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You rewrite the list each time but only add the eventlistener the very first time
Instead delegate
$("#main").on("click",".delete-button", function() {
const names = Number(this.id);
sales.splice(names, 1);
makeEntries(sales)
})
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$("#main").on("click",".delete-button", function() {
const names = Number(this.id);
sales.splice(names, 1);
makeEntries(sales)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>
Alternatively do not rewrite
$(".delete-button").on("click", function() {
const names = Number(this.id);
sales.splice(names, 1);
$(this).closest(".main-page").remove()
})
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$(".delete-button").on("click", function() {
const names = Number(this.id);
sales.splice(names, 1);
$(this).closest(".main-page").remove()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>

How to add external data to javascript for jquery auto complete

I'm trying to make a auto complete search bar using jquery autocomplete. The thing is I need to display Json data from an external site into my search bar.
Whenever I try to put the data as such from json into the script, it's working. But when I refer external url it refuses to work.
I tried implementing all json data into my script. But it takes so long to process as there will be more than 40000+ lines in my html page.
The Json link for the data which I have to display is here
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": [
{
"symbol": "AACG",
"name": "ATA Creativity Global American Depositary Shares",
"lastsale": "$2.19",
"netchange": "-0.45",
"pctchange": "-17.045%",
"volume": "1408435",
"marketCap": "68715455.00",
"country": "China",
"ipoyear": "",
"industry": "Service to the Health Industry",
"sector": "Miscellaneous",
"url": "/market-activity/stocks/aacg"
},
{
"symbol": "AACI",
"name": "Armada Acquisition Corp. I Common Stock",
"lastsale": "$9.88",
"netchange": "0.01",
"pctchange": "0.101%",
"volume": "8345",
"marketCap": "204609860.00",
"country": "United States",
"ipoyear": "2021",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aaci"
}],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
The above code works and the below code doesn't.
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": ["https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json"
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
Looking for a solution to add this and also for a solution to reduce the json key pair with only "symbol" and "name" from each corresponding data in the link.
Try this:
function toAutocomplete(dt, keyvar){
let rli = [];
for (let i = 0; i < dt.length; i++) rli.push(dt[i][keyvar]);
return rli;
}
function inArrayAutocompleteSelected(key, array_autocomplete, array_master){
let x = array_master[$.inArray(key, array_autocomplete)];
return x;
}
$('#id_ticker').autocomplete({ source: [], minLength: 1 });
// $('#id_ticker').autocomplete("disable");
let url = 'https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json';
let r = _ajax('GET', url, ''); // your ajax script
console.log(r);
let liAuto = toAutocomplete(r, 'name');
console.log(liAuto);
$('#id_ticker').autocomplete("option", "source", liAuto );
// $('#id_ticker').autocomplete("enable");
$("#id_ticker").autocomplete({
select: function( event, ui ) {
console.log(ui, ui.item);
getData = inArrayAutocompleteSelected(ui.item.value, liAuto, r);
console.log(getData);
}
});

How to get row id of particular row from legacy jQuery data table

I had gone through
http://www.gyrocode.com/articles/jquery-datatables-checkboxes/
It shows a nice way to retrieve row id
// Handle click on checkbox
$('#example tbody').on('click', 'input[type="checkbox"]', function(e){
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
However, I need to stick with legacy DataTable 1.9.4. I try to perform the similar thing.
$('#confirm-table').on('click', 'input[type="checkbox"]', function() {
var $row = $(this).closest('tr');
var data = table.fnGetData($row[0]);
var rowId = data[0];
// I expect to get "123" or "456". But I am getting '<input type="checkbox">'
alert(rowId);
})
As you can see, what I did is I convert current DataTable code from
var data = table.row($row).data();
to legacy DataTable code
var data = table.fnGetData($row[0]);
However, instead of getting row id ("123" or "456"), I'm getting rendered code <input type="checkbox">
Any idea how to do it in proper way?
https://jsfiddle.net/14p9uu8c/
Here's the fully workable code to demonstrate the problem
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.9.4/js/jquery.dataTables.js"></script>
</head>
<body>
<table id="confirm-table">
</table>
<script>
$(document).ready(function (){
var dataSet = [
[ "123", "System Architect" ],
[ "456", "Accountant" ]
];
table = $('#confirm-table').dataTable( {
aaData: dataSet,
aoColumns: [
{ sTitle: "Id" },
{ sTitle: "Job" }
],
"aoColumnDefs":[ {
"aTargets": [0],
"fnRender": function ( oObj ) {
return '<input type="checkbox">';
}
}]
} );
$('#confirm-table').on('click', 'input[type="checkbox"]', function() {
var $row = $(this).closest('tr');
var data = table.fnGetData($row[0]);
var rowId = data[0];
// I expect to get "123" or "456". But I am getting '<input type="checkbox">'
alert(rowId);
});
});
</script>
</body>
</html>
First of all we need to convert your existing aaData to json objects. Then we have our aoColumns to match our aaData. After it's done lets update aoColumnDefs.
Instead of rendering our DT_RowId column content as a checkbox, lets hide our that column so we can easily access the DT_RowId data.
I did not change your onClick listener.
Here is working example:
$(document).ready(function (){
var dataSet = [
{
"DT_RowId": "123",
"checkbox": "",
"job": "System Architect"
},
{
"DT_RowId": "456",
"checkbox": "",
"job": "Accountant"
}
];
table = $('#confirm-table').dataTable( {
"bProcessing": true,
aaData: dataSet,
aoColumns: [
{ "mData": "DT_RowId" , sTitle: "Hidden row Id" },
{ "mData": "checkbox" , sTitle: "Id" },
{ "mData": "job", sTitle: "Job" } // <-- which values to use inside object
],
"aoColumnDefs":[
{
"aTargets": [0],
"bVisible": false
},
{
"aTargets": [1],
"fnRender": function ( oObj, value ) {
return '<input type="checkbox">';
}
}
]
} );
$('#confirm-table').on('click', 'input[type="checkbox"]', function() {
var $row = $(this).closest('tr');
var data = table.fnGetData($row[0]);
var rowId = data[0];
// I expect to get "123" or "456". But I am getting '<input type="checkbox">'
console.log(data.DT_RowId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.9.4/js/jquery.dataTables.js"></script>
<table id="confirm-table">
</table>

Issue on Loading Dynamic Data to "DataTables" Using jQuery

Demo
I am using this solution to load dynamic data in to Data Table. I have to use the Array of Array since I am getting dynamic data from user on font end selection (NO DATABASE Selection).
I am using following code to upload data into the table
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example"></table>
and JS:
$(document).ready(function () {
var counter = 0;
var compareTable = [];
var compareRow = [];
var check = "Test";
var compModelName = "Test";
var selectedType = "Test";
var selectedTarget = "Test";
var selectedROR = "Test";
var selectedSpecies = "Test";
var historicDis = "Test";
var projectsNumber = "Test";
var projectsCost = "Test";
var projectsRoads = "Test";
var projectsPowerline = "Test";
var projectsPenstock = "Test";
var mapshow = "Test";
$("#load").on("click", function () {
loader();
});
function loader() {
compareRow.push(check);
compareRow.push(compModelName);
compareRow.push(selectedType);
compareRow.push(selectedTarget);
compareRow.push(selectedROR);
compareRow.push(selectedSpecies);
compareRow.push(historicDis);
compareRow.push(projectsNumber);
compareRow.push(projectsCost);
compareRow.push(projectsRoads);
compareRow.push(projectsPowerline);
compareRow.push(projectsPenstock);
compareRow.push(mapshow);
}
$('#example').dataTable( {
"data": compareTable,
"columns": [
{ "title": "Compare" },
{ "title": "Model Name" },
{ "title": "Model Type" },
{ "title": "Energy Target" },
{ "title": "ROR Attribute" },
{ "title": "Species", "class": "center" },
{ "title": "Disturbance", "class": "center" },
{ "title": "Projects" },
{ "title": "Cost (M$)" },
{ "title": "Roads (Km)" },
{ "title": "Powerlines (Km)", "class": "center" },
{ "title": "Penstock (m)", "class": "center" },
{ "title": "Map" }
]
} );
});
});
but as you can see in the Demo it is not functioning when we click on the "#load". Can you please let me know why this is happening and how I can fix it?

Multiple Datatables on dynamic tabs

i have developed a dynamic tab mechanism for my web application that any internal content will load using ajax in a new tab which will be appended at the last active tab something like tab functionality in browsers for executing loaded content js i simply have a namespace custom html5 data tag witch is the name of the script and i execute the init() method of it when a new tab is created, it works well on simple jquery scripts but when i try to load pages with jQuery Datatable in them which i'm using for reports my report filter form only works on the last datatable, i have no idea how to solve this issue, here is my tabs.js and reports.js code the second one is the Datatable javascripts.
tabs.js:
(function() {
// open e new tab:
var tabs_label = 1;
var tab_id = 1;
var tabs_num = 1;
var defaults_open = false;
var reports_open = false;
var ns ;//needs change
$('.tab-link').live('click',function(e) {
var parent = $(this);
var href = $(this).attr('href');
if (href == '/defaults/' && defaults_open){
e.preventDefault();
bootbox.alert('تب تعریف پیش فرض ها باز می باشد!');
}
// else if(href == '/report/' && reports_open){
// e.preventDefault();
// bootbox.alert('تب گزارش ها باز می باشد');
// }
else{
var tab_name = $(this).attr('data-name');
e.preventDefault();
tab_id ++;
if (tabs_num > 6) {
bootbox.alert('تب های باز شده بیش از حد مجاز است.');
}
else {
$('.tab-pane').filter('.active').removeClass('active');
$.blockUI({ message: $('#wait-icon'), css: {width: '64px', height: '64px' }});
var content = $('<div></div>', {
class:"tab-pane dynamic-tab active",
id:tab_id,
});
content.appendTo('div#main-tabs');
$('ul.nav-tabs li.active').removeClass('active');
var new_li = $("<li class='active' data-type='"+href+"'><a style='float:left' class='tabbtn' href="+tab_id+" data-toggle='tab'>"+tabs_label+" - "+tab_name+"</a><a style='float:right' class='close' id='tabClose'><i class='icon-remove'></i></a></li>")
new_li.appendTo('ul#tabs');
content.load( href + ' div#arya', function(response, status, xhr) {
if(parent.attr('namespace')){
ns = eval(parent.attr('namespace'));
if(ns.root){
ns.root = content;
}
ns.init();
}
$.unblockUI();
if(status == 'error'){
bootbox.alert("در حال حاضر سرور با مشکل مواجه است", "خروج", function(){
new_li.find("a.close").trigger('click');
});
}
});
tabs_num++;
tabs_label++;
if(href == '/defaults/'){
defaults_open = true;
}
else if(href == '/report/'){
reports_open = true;
}
}
}
});// sell tab name needs work.
// tab activatior function
$('#tabs a.tabbtn').live('click', function(e) {
e.preventDefault();
var id = $(this).attr('href');
var selector = 'div#' + id;
$('.dynamic-tab').filter('.active').removeClass('active');
var new_tab = $('.dynamic-tab').filter(selector);
new_tab.addClass('active');
console.log(new_tab);
ns.root = new_tab;
});
// close a tab:
$('a#tabClose').live('click', function(e) {
e.preventDefault();
$this = $(this);
var a = $this.siblings('a');
var li = $this.parent();
console.log(li);
if(li.attr('data-type') == '/defaults/'){
defaults_open = false;
}
else if(li.attr('data-type') == '/report/'){
reports_open = false;
}
var id = a.attr('href');
var div = $('div#' + id);
if (div.hasClass('active')){
var last = div.siblings('div.tab-pane').last();
last.addClass('active');
ns.root = last;
}
div.detach();
var li = a.parent();
if (li.siblings('.active').length == 0){
li.siblings('li').last().addClass('active');
}
li.detach();
tabs_num--;
tabs_label--;
});
})();
reports.js:
var reports = {
'root': $('.tab-pane#defaults_init'),
'table_init': function() {
var oTable;
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource ) {
if ( typeof sNewSource != 'undefined' )
oSettings.sAjaxSource = sNewSource;
console.log($(this));
this.fnClearTable( this );
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var myData = new Array({ "name": "name", "value": reports.root.find('#name').val()}, { "name": "family", "value": reports.root.find('#family').val()}, { "name": "national_id", "value": reports.root.find('#national_id').val()}, { "name": "city", "value": reports.root.find('#city').val()}, { "name": "job", "value": reports.root.find('#job').val()}, { "name": "date_from", "value": reports.root.find('#date_from').val()}, { "name": "date_to", "value": reports.root.find('#date_to').val()}, { "name": "age_from", "value": reports.root.find('#age_from').val()}, { "name": "age_to", "value": reports.root.find('#age_to').val()}, { "name": "credit_from", "value": reports.root.find('#credit_from').val()}, { "name": "credit_to", "value": reports.root.find('#credit_to').val()});
$.ajax({
url: oSettings.sAjaxSource,
dataType: 'json',
data: myData,
type: "POST",
success: function(json) {
/* Got the data - add it to the table */
for ( var i=0 ; i<json.aaData.length ; i++ ) {
that.oApi._fnAddData( oSettings, json.aaData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw( that );
that.oApi._fnProcessingDisplay( oSettings, false );
}
});
}
},
'init': function(){
oTable = reports.root.find('.targetTable').dataTable( {
"sDom": "<'row-fluid'r<'span12'l>>t<'row-fluid'<'span6'p><'span6'i>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sUrl": "/media/translation/dataTables.persian.txt"
},
"sAjaxSource": "/report/ajax/customers/",
"sServerMethod": "POST",
"bDestroy": true,
// "bRetrieve": true,
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "name", "value": reports.root.find('#name').val()} );
aoData.push( { "name": "family", "value": reports.root.find('#family').val()});
aoData.push( { "name": "national_id", "value": reports.root.find('#national_id').val()} );
aoData.push( { "name": "city", "value": reports.root.find('#city').val()} );
aoData.push( { "name": "job", "value": reports.root.find('#job').val()} );
aoData.push( { "name": "date_from", "value": reports.root.find('#date_from').val()} );
aoData.push( { "name": "date_to", "value": reports.root.find('#date_to').val()} );
aoData.push( { "name": "age_from", "value": reports.root.find('#age_from').val()} );
aoData.push( { "name": "age_to", "value": reports.root.find('#age_to').val()} );
aoData.push( { "name": "credit_from", "value": reports.root.find('#credit_from').val()} );
aoData.push( { "name": "credit_to", "value": reports.root.find('#credit_to').val()} );
console.log(aoData);
},
"aoColumns": [
{ "mDataProp": "name" },
{ "mDataProp": "family" },
{ "mDataProp": "national_id" },
{ "mDataProp": "birthday" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "phone" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "cellphone" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "email" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "city" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "country" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "address" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "job" },
{ "mDataProp": "credit" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "age" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "creation_time" ,"bSearchable": false, "bVisible": false},
],
} );
/* Add a click handler to the rows - this could be used as a callback */
$('#targetTable tbody tr').live('click', function () {
var aData = oTable.fnGetData( this );
infoTpl = "<div class='row-fluid span12'><table class='table table-striped'><tbody>";
infoTpl += "<tr><td>نام: <span>"+aData['name']+"</span></td><td>نام خانوادگی: <span>"+aData['family']+"</span></td><td>کد ملی: <span>"+aData['national_id']+"</span></td><td>تاریخ تولد: <span>"+aData['birthday']+"</span></td></tr>";
infoTpl += "<tr><td>تلفن: <span>"+aData['phone']+"</span></td><td>تلفن همراه: <span>"+aData['cellphone']+"</span></td><td colspan='2'>ایمیل: <span>"+aData['email']+"</span></td></tr>";
infoTpl += "<tr><td colspan='2'>آدرس: <span>"+aData['address']+"</span></td><td>شهر: <span>"+aData['city']+"</span></td><td>کشور: <span>"+aData['country']+"</span></td></tr>";
infoTpl += "<tr><td>سن: <span>"+aData['age']+"</span></td><td>میزان اعتبار: <span>"+aData['credit']+"</span></td><td>تاریخ ایجاد در سیستم: <span>"+aData['creation_time']+"</span></td></tr>";
infoTpl += "</tbody></table></div>";
reports.root.find('#targetInfo').html(infoTpl);
reports.root.find('#targetInfo > div > table > tbody > tr > td > span').css("color","navy");
$(this).toggleClass('row_selected');
} );
reports.root.find('#queryForm').submit(function() { // catch the form's submit event
oTable.fnReloadAjax();
return false;
});
},
};
$(document).ready(function () {
reports.table_init();
});

Categories

Resources