DataTable ajax Nested Table with search - javascript

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.

Related

Show an image in a "Jquery Datatable Plugin" cell using "columns.render" callback

I'm trying to display an image in a cell using the suggested answer from this post: Displaying image on Datatable.
However, the first parameter of the callback (data) should receive the string with the url pointing to the image, but it is always undefined.
This is how I initialize the datatable (columnDefs contains the callback I was talking about):
$().ready(function () {
var opt = {
columnDefs: [{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
};
$('#dataTable').DataTable(opt);
});
After an ajax call, I update data into the table, drawing it back again:
$('#cmbSeasons').change(function () {
var leagueId = parseInt($('#cmbLeagues').val().toString());
var seasonYear = parseInt($('#cmbSeasons').val().toString());
var settings = {
url: '/Standing/Read/Standings',
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: { leagueId: leagueId, seasonYear: seasonYear },
success: function (data) {
var t = $('#dataTable').DataTable();
t.clear();
for (var i = 0; i < data.length; i++) {
t.row.add([
data[i].rank,
data[i].teamName,
data[i].teamLogo,
data[i].points,
data[i].allPlayed,
data[i].allWin,
data[i].allDraw,
data[i].allLose,
data[i].allGoalsFor,
data[i].allGoalsAgainst,
data[i].homePlayed,
data[i].homeWin,
data[i].homeDraw,
data[i].homeLose,
data[i].homeGoalsFor,
data[i].homeGoalsAgainst,
data[i].awayPlayed,
data[i].awayWin,
data[i].awayDraw,
data[i].awayLose,
data[i].awayGoalsFor,
data[i].awayGoalsAgainst
]);
}
t.draw();
},
error: function (result) { alert('error ' + result.status + ': ' + result.responseText); }
};
$.ajax(settings);
});
The third column (data[i].teamLogo) contains the correct url I want to use as src for the image (I'm sure about it because I used the developer console to check the correctness of the string).
This is html Markup:
<table id="dataTable" class="text-center">
<thead class="text-capitalize">
<tr>
<th class="all">Rank</th>
<th class="all">Team</th>
<th class="all">Logo</th>
<th class="all">Pts</th>
<th class="all">Pl</th>
<th class="all">W</th>
<th class="all">D</th>
<th class="all">L</th>
<th class="all">GF</th>
<th class="all">GA</th>
<th class="all">HPl</th>
<th class="all">HW</th>
<th class="all">HD</th>
<th class="all">HL</th>
<th class="all">HGF</th>
<th class="all">HGA</th>
<th class="all">APl</th>
<th class="all">AW</th>
<th class="all">AD</th>
<th class="all">AL</th>
<th class="all">AGF</th>
<th class="all">AGA</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Is there anything wrong with the callback I wrote? Should be "data" parameter populated with a different string, instead of 'teamLogo'?
I'm using the latest version of datatables (1.10.20) and Jquery (3.5.1).
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
use an Img object to return instead
https://www.w3schools.com/jsref/dom_obj_image.asp
Changing the definition of the options this way:
$().ready(function () {
let opt: DataTables.Settings = {
columns: [
{ "data": "rank" },
{ "data": "teamName" },
{ "data": "teamLogo" },
{ "data": "points" },
{ "data": "allPlayed" },
{ "data": "allWin" },
{ "data": "allDraw" },
{ "data": "allLose" },
{ "data": "allGoalsFor" },
{ "data": "allGoalsAgainst" },
{ "data": "homePlayed" },
{ "data": "homeWin" },
{ "data": "homeDraw" },
{ "data": "homeLose" },
{ "data": "homeGoalsFor" },
{ "data": "homeGoalsAgainst" },
{ "data": "awayPlayed" },
{ "data": "awayWin" },
{ "data": "awayDraw" },
{ "data": "awayLose" },
{ "data": "awayGoalsFor" },
{ "data": "awayGoalsAgainst" }
],
columnDefs:
[{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
}
$('#dataTable').DataTable(opt);
});
and simplifying the for loop like this:
t.rows.add( data ).draw();
did the trick!
It seemes that I had to define the data columns for the callback to work properly.

Getting 500 while adding data to datatables in javascript .net mvc

So i'm trying to add data to datatable, i'm relatively new to Web Applications, i'm more of a mobile app developer
I've looked into a few examples and i've come up with a solution to do it, but for some reason i'm getting this error on chrome
DataTables warning: table id=personaliseDatatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
And if i check the console i'm getting Internal Server Error 500, but in fact the controller is getting triggered and i'm able to get the data from the repository, but its not able to return is what i'm able to understand
This is my method in controller
public JsonResult GetAllCapacityData()
{
try
{
var data = _capacityService.GetAllData(null).ToList();
return Json(new
{
data = data
});
}
catch (Exception ex)
{
_logger.Error("WebApp -> AreaMappingController -> GetAllData -> Catch -> ", ex);
throw;
}
}
and this is my ajax request
$(document).ready(function() {
if ($('#loaderDiv').hasClass("show")) {
$('#loaderDiv').removeClass("show");
}
GetCapacityData();
});
function GetCapacityData() {
$('#personaliseDatatable').DataTable({
responsive: true,
processing: false,
serverSide: false,
searching: true,
scrollX: true,
bDestroy: true,
"scrollX": true,
aaSorting: [0, 'desc'],
ajax: {
url: '#Url.Action("GetAllCapacityData", "Capacity")',
type: 'POST'
},
language: {
search: "",
searchPlaceholder: "Search...",
sInfoFiltered: ""
},
columns: [{
"render": function(data, type, full, meta) {
return meta.row + 1;
}
},
{
data: "data.ZoneMaster.ZoneName"
},
{
data: "CateogoryName"
},
{
data: "SubCateogoryName"
},
{
data: "ServiceType"
},
{
data: "UserType"
},
{
data: "Division"
},
{
data: "SlotName"
},
{
data: "AllowBooking"
},
{
data: "HoursBlockAhead"
},
{
data: "DaysOpenAheadForBooking"
},
{
data: "MaximumOrderCapacity"
},
{
mRender: function(data, type, row) {
return '<a class="actionLinks" data-toggle="tooltip" title="View Details" style="cursor:pointer;" onclick="EditCapacity(' + row.CapacityPlannerId + ')">Edit</a>';
},
sortable: false,
searchable: false
}
]
});
alert(data.ZoneMaster.ZoneId);
}
And this my Datatable
<div class="card-body">
<table style="width:100%" class="table table-striped table-hover table-bordered" id="personaliseDatatable">
<thead>
<tr>
<th>#</th>
<th>Zone</th>
<th>Cateogory</th>
<th>Sub Cateogory</th>
<th>Service Type</th>
<th>User Type</th>
<th>Division</th>
<th>Slot Name</th>
<th>Allow Booking</th>
<th>Hours to Block Ahead</th>
<th>Days Open Ahead</th>
<th>Max. Order Capacity</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Error on console
POST http://localhost:53201/Capacity/GetAllCapacityData 500 (Internal Server Error)
Any Help would be deeply appreciated

checkbox click event with jquery datatables not working

I have used jQuery Datatables https://datatables.net/ for my grids.
There are two grids, each has a checkbox in the grid. I need to generate an event when checkbox is checked/unchecked.
I have tried this but it doesn't work. Please let me know what I am doing wrong here..........
$(document).ready(function () {
$('.cBSAGrid tr td').click(function (event) {
alert('0');
});
});
and
$(document).ready(function () {
$('#BSAGrid tr').click(function (event) {
alert('0');
});
});
My datatable jquery
$.ajax({
type: "POST",
url: "/BSA/BSAExceptionGrid",
data: '{ policynumber: "' + txtpolicy.val() + '",clientname:"' + clientname.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
div.css("display", "none");
$('#BSAGrid').DataTable({
paging: false,
searching: false,
destroy: true,
"bInfo" : false,
data: response,
columns: [
{ "data": "Logged_ID" },
{ "data": "Logged_ID" },
{ "data": "CustomerName" },
{ "data": "ClientType" }
],
aoColumnDefs: [
{
aTargets: [0], // Column number which needs to be modified
mRender: function (o, v) { // o, v contains the object and value for the column
return '<input type="checkbox" id="chkBSA" name="chkBSA" />';
}
//,sClass: 'tableCell' // Optional - class to be applied to this table cell
}
,
{
aTargets: [1],
visible: false
}
],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
},
failure: function (response) {
alert(response);
},
error: function (response) {
alert(response.responseText);
}
});
HTML
<div id="BSAGridContainer" style="display:none;">
<table id="BSAGrid" class="cBSAGrid table table-responsive">
<thead>
<tr>
<th></th>
<th >Logged_ID</th>
<th>Client Name</th>
<th>Client Type</th>
</tr>
</thead>
</table>
</div>
Try bellow code:
$(document).ready(function(){
$(document).on("change", "#chkBSA", function() {
alert('click')
});
});
You could include the onChange event listener in the same column adding this into your column return text onChange="gridCheckboxChange(this);"
If you're using bootstrap 4 custom-checkbox then add a class into your checkbox
.className {left: 0;z-index: 1;width: 1.25rem;height: 1.25rem;}

How to get all checkbox values in cells

I have jQuery datatables with some checkboxes for granting privileges.
I need to get table values to a array. Please enlighten me about how to get checkbox states inside cells, not only the checked ones. Thank you.
My table
<table id="jqueryTable" name="tt" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th name="id">
ID
</th>
<th name="name">
PRIV_Name_Str
</th>
<th name="create">
Create
</th>
<th>
Edit
</th>
<th>
View
</th>
</tr>
</thead>
<table>
My datatable query
function LoadProduct(element) {
$.ajax({
url: '/ADM_MAS_Privilege/GetFormData',
data: { YourValue: $('#productCategory').val() },
method: 'post',
dataType: 'json',
success: function (data) {
var table = $('#jqueryTable').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
bDestroy: true,
"columnDefs":
[{
"targets": [2, 3, 4],
"render": function (data, type, row, meta) {
console.log("XX " + meta.row + " " + meta.col);
return type === 'display' ?
'<input type="checkbox" id="p" class="chk" name="group' + meta.row + '" /> ' + data :
data;
columns: [{ "data": "ID", "ID": "ID", "autoWidth": true },
{
"data": "PRIV_Name_Str", "PRIV_Name_Str": "PRIV_Name_Str", "autoWidth": true
},
{
"data": "Create", "Create": "Create", "autoWidth": true
},
{ "data": "Edit", "Edit": "Edit", "autoWidth": true },
{
"data": "View"
}
]
});
}
});
};
My jQuery function to read datatable
$('#upload').click(function () {
var table = document.getElementById("jqueryTable");
var tableArr = [];
for (var i = 1; i < table.rows.length; i++) {
tableArr.push({
ID: table.rows[i].cells[0].innerHTML,
PRIV_Name_Str: table.rows[i].cells[1].innerHTML,
Create: table.rows[i].cells[2].innerHTML,
Edit: table.rows[i].cells[3].innerHTML,
View: table.rows[i].cells[4].innerHTML
});
}
});
I tried table.rows[i].cells[2].innerHTML.getElementById("p").checked even and it's not working.
Since you are using jQuery:
document.getElementById("jqueryTable").each(function (index, element) {
tableArr.push({
ID: element.cells[0].innerHTML,
PRIV_Name_Str: element.cells[1].innerHTML,
Create: element.cells[2].innerHTML,
Edit: element.cells[3].innerHTML,
View: element.cells[4].innerHTML
})
})
You can find the element and the checked property within each cell:
for (var i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
tableArr.push({
ID: cells[0].innerHTML,
PRIV_Name_Str: cells[1].innerHTML,
Create: cells[2].querySelectorAll('input')[0].checked,
Edit: cells[3].querySelectorAll('input')[0].checked,
View: cells[4].querySelectorAll('input')[0].checked
});
}

jquery/javascript are not working inside ng-view

I'm trying to achieve SPA with help angular route provide for that i'm using ng-view for injecting the views. in one page i'ave a jquery datatable where i need to get the index of row selected by using jquery. but this is not happing inside ng-view. i tried by using directives also but no luck.
can someone help me in this
Home.html
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
Get Selected Rows
Controller.Js:
app.controller("HomeController", function ($scope, $http,$window) {
$('#example').DataTable({
"ajax": {
"url": "test.json",
"dataSrc": ""
},
"columns": [
{ "data": null },
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
$scope.$broadcast('dataloaded');
$scope.Customers = $("example").DataTable().data;
console.log("Result: ", $scope.Customers.length);
$scope.GetDetails = function () {
var table = $("example").DataTable();
var rowid = table.row(this).index();
alert(rowid);
};
$scope.GetRowID = function () {
$('#example tbody').on('click', 'tr', function () {
console.log("inside");
debugger;
var table = $("#example").DataTable();
alert('Row index: ' + table.row(this).index());
});
};
$scope.init();

Categories

Resources