jQuery DataTable add dynamic columns - javascript

I have a JSON object like below (dataSource) in that JSON object the property 'viewClasses' sometimes comes as blank, here what I want to do is if 'viewClasses' have any record I want to add a dynamic column to the table and the name of the column header will be the value of 'viewClasses.class', I have tried the below code but it's not working as expected.
Here is the result of the below code -
Here how I want this to be-
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var column = [];
function AddColumn() {
$.each(dataSource[0].viewDetails.viewClasses[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
column.push(my_item);
});
}
$('#example').dataTable({
data: dataSource[0].viewDetails.viewClasses,
"columns": column,
"paging": false,
"bInfo": false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<style src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="example" class="table table-striped" width="100%"></table>
</div>
</div>
</div>

Your source data needs to be iterated in two different ways, to build the two different dynamic arrays which DataTables needs: - column data and row data.
Firstly you have two columns, A and B. To build the array for these, you can use the following:
var dynamicColumns = [];
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
});
I chose not to use the jQuery iterator because I want access to each object in the array.
This gives me the following structure:
[
{
"data": "A",
"title": "Heading A"
},
{
"data": "B",
"title": "Heading B"
}
]
But for the table's data, I want to end up with only one row of data:
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
Here, I end up with the following:
[
{
"A": 2000,
"B": 3000
}
]
Now I have the structures I need for my DataTable initialization. The overall script therefore is as follows:
<script type="text/javascript">
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var dynamicColumns = [];
var dynamicRows = [];
function buildDynamicData() {
var columnData = dataSource[0].viewDetails.viewClasses;
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
}
buildDynamicData();
console.log(dynamicColumns);
console.log(dynamicRows);
$(document).ready(function() {
$('#example').DataTable({
columns: dynamicColumns,
data: dynamicRows,
paging: false,
info: false
});
} );
</script>
And the end result looks like this (in my test environment):

Related

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 value from each datatable row dropdownlist

I'm working with Datatable. The problem is I need to get all the values from each row's dropdownlist. The datatable have the column 'Company' which the user need to select value from dropdownlist .Now I'm able to get each row's value for Citizen_ID and Tel using the code below.
var rowData = table.rows().data();
var dataArr = [];
$.each($(rowData), function(key,value){ //data
let tempObj = {
Citizen_id: value["Citizen_ID"],
Tel: value["Tel"]
}
dataArr.push(tempObj);
});
How can I get selected value from dropdownlist for all datatable pages?.
I would approach this in a slightly different way.
Some of the data you need can be accessed from the DataTable, but the selected value in each row's drop-down list only exists in the DOM, so you need the related DOM node to access that data.
I would therefore populate the following two variables, at the start:
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
Both of these are populated using DataTables API calls, so the entire table is processed.
This gives you two arrays - one with the DataTables data objects for each row, and the other with the DOM nodes.
Then you can use a traditional for loop to iterate the arrays in parallel, and extract the specific pieces of data you need.
For the drop-down node, you can use a jQuery selector:
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
I used a class (value = company) in the HTML code for the select, just in case there are multiple different selects in one row.
Here is a demo of the overall approach:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
</table>
<br>
<button id="data_btn" type="button">Get Data</button>
</div>
<script>
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
];
$(document).ready(function() {
var table = $('#example').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Company",
defaultContent: '',
render: function ( data, type, row, meta ) {
if (type === 'display') {
return '<select class="company">'
+ '<option value="Google">Google</option>'
+ '<option value="Microsoft">Microsoft</option>'
+ '<option value="Amazon">Amazon</option></select>';
} else {
return data;
}
}
},
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
]
} );
$("#data_btn").on( "click", function() {
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
var dataArr = [];
for (i = 0; i < rowData.length; i++) {
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
let tempObj = {
id: rowData[i].id,
name: rowData[i].name,
company: selectedCompany
}
dataArr.push(tempObj);
}
console.log( dataArr );
});
} );
</script>
</body>
</html>
When you run the demo, first select a "company" value in each of the drop-downs.
Then click the "Get Data" button.
The resulting object will look similar to the following:
[
{
"id": "123",
"name": "Tiger Nixon",
"company": "Amazon"
},
{
"id": "456",
"name": "Donna Snider",
"company": "Microsoft"
}
]

Adding a child to any parent on Angular UI Tree pushes it to every parent

I have been playing around with the Angular UI Tree drag and drop and have come by an issue that has stumped me. The json is being received from my services. When it is received by my controller, I must format it properly with an empty array so it will be able to hold childen:
Formatting:
function categorySuccessPost(data) {
var emptyCategoryArray = {
Categories: []
}
for (var i = 0; i < data.length; i++) {
$.extend(data[i], emptyCategoryArray);
}
$scope.categoryData = data;
}
It is now formatted and looks like:
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [] }, { "CategoryId": 23267, "MerchantId": 5594,
"ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon",
"DateCreated": "/Date(-62135596800000-0000)/", "IsActive": true, "IsDefault":
true, "ItemCount": 1, "ResponseStatus": { "ErrorCode": "SUCCESS" },
"TotalRecordCount": 15, "Categories": [] } }
I have tried two different functions when attempting to add a child:
Function 1 (Uses model value):
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
Function 2 (Uses index of object in the array, and yes, I have made sure the correct index is being passed):
$scope.newSubItem = function (index) {
var array = $scope.categoryData;
array[index].Categories.push({
CategoryId: 12312,
Name: 'test',
Categories: []
});
};
The issue is that instead of pushing the new data to the selected index, it adds the json to every Categories :
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [ { "CategoryId": 12312, "Name": "test", "Categories": [] } ] }, {
"CategoryId": 23267, "MerchantId": 5594, "ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon", "DateCreated": "/Date(-62135596800000-
0000)/", "IsActive": true, "IsDefault": true, "ItemCount": 1, "ResponseStatus":
{ "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15, "Categories": [ {
"CategoryId": 12312, "Name": "test", "Categories": [] } ] }
I am not showing the HTML because it does not appear to be an issue. Here's where I have narrowed it down to, but still have no explanation:
If I use the data that goes through the $.extend method then it adds a child to every parent. But if I copy the json that is generated after the formatting, put it into and object and then read from that, then it only adds a child to the selected parent like I want. But it is necessary to add the empty array. Any idea why this is happening and any solution?
EDIT
One more piece of information that may be important: When I add a full Category (different function), rather than adding a subcategory and then try to add a child to the newly generated category then it works correctly (adding only a child to that category):
$scope.addCategory = function () {
var name = $scope.categoryName;
// Temporary
var categoryId = Math.floor((Math.random() * 50000) + 1)
console.log(name, categoryId)
$scope.categoryData.unshift({ CategoryId: categoryId, Name: name, Categories: [] })
$scope.categoryName = "";
$("#addCategoryModal").modal('hide');
Notification.success({ message: 'Category Added Successfully!', delay: 3000 });
}
I'm still not sure exactly why this is happening, but this was my solution to fixing the issue:
Remove the $.extend for loop and $.extend function:
function categorySuccessPost(data) {
$scope.categoryData = data;
}
When adding an item, check if the array has been initialized, if not, create it in the current scope:
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
if(currentCategoryData.Categories === 'undefined'){
currentCategoryData.Categories = [];
}
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
The issue with this method is that you can no longer drag a node into an empty parent.

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?

Getting complex attribute value of object

Given json like this :
{ "rss": {
"page": 1,
"results": [{
"type": "text",
"$": 10
}],
"text": [{
"content": "Lorem ipsum dolor sit amet.",
"author": {
"name": "Cesar",
"email": "cesar#evoria.com"
},
},
{
"content": "Tema Tis rolod muspi merol.",
"author": {
"name": "Cleopatre",
"email": "cleopatre#pyramid.com"
},
}]
}
In javascript, I can retrieve value like this :
var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
// this one is ok
var content = val['content'];
// this one does not work
var authorname = val['author.name'];
});
Is this a way, given the attribute name in a string format, to retrieve the value of a complex object, for instance json.text[0].author.name?
EDIT
I would like to store the needed attributes in another object like :
[
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name"}
]
You can split your "index" by . and loop over "segments", descending through levels on each iteration.
var obj = {
author : {
name : "AuthorName"
}
}
function get_deep_index(obj, index) {
var segments = index.split('.')
var segments_len = segments.length
var currently_at = obj
for(var idx = 0; idx < segments_len; idx++) {
currently_at = currently_at[segments[idx]]
}
return currently_at
}
console.log(get_deep_index(obj, 'author.name'))
The following should fix the problem.
var authorname = val['author']['name'];
You can also store the object itself as:
var author = val['author'];
And then later on you can index the attributes from that.
console.log(author.name, author.email)
Yent give a good hint in the comments with the eval function. I resolve my needed with this kind of code:
var json = JSON.parse(myjsonasastring);
var descriptiontobeadded = [
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name" }
];
$.each(descriptiontobeadded, function(key, val) {
var dt = '<dt>' + val.dt + '</dt>';
description.append(dt);
var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
description.append(dl);
});

Categories

Resources