Unable to accessing Array with JQuery and Display on Table - html

Trying to Display the : Name | Industry | Current Price to the HTML Table .
Please review my Code and help me display my data on HTML page .
Am i missing something to not able to Display on the HTML ?
Is my way of accessing the array wrong ?
This is my test.js script
$(document).ready(function () {
var test_data = [
{
"current_price": 1626.0,
"name": "HDFC Bank",
"industry": "Financials",
},
{
"current_price": 7064.8,
"name": "Maruti Suzuki",
"industry": "Automobiles",
}
];
$.each( data, function( key, val ) {
test_data += '<tr>' ;
test_data += '<td>'+val.name+"<td>" ;
test_data += '<td>'+val.industry+"<td>" ;
test_data += '<td>'+val.current_price+"<td>" ;
s_data += '</tr>' ;
});
$('#test').appendTo(test_data);
});
Below is my **HTML Page** :
<html>
<head>
Test
</head>
<body>
<table class="table table-hover" id="test">
<thead>
<tr>
<th>Company Name</th>
<th>Industry </th>
<th>Current price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/test.js"></script>
</body>
</html>

There are lots of issues with the code. Mostly with names. For example test_data is the array of data but then test_data is where html is built! Then the jquery loop is iterating through data (and not test_data). Then what is s_data? a typo! Then the closing TDs are missing and then the test_data should be appended to Table and not the other way around.
Here is the working code (and here is the JsFiddle):
$(document).ready(function () {
var data = [
{
"current_price": 1626.0,
"name": "HDFC Bank",
"industry": "Financials",
},
{
"current_price": 7064.8,
"name": "Maruti Suzuki",
"industry": "Automobiles",
}
];
var test_data = '';
$.each( data, function( key, val ) {
test_data += '<tr>' ;
test_data += '<td>'+val.name+"</td>" ;
test_data += '<td>'+val.industry+"</td>" ;
test_data += '<td>'+val.current_price+"</td>" ;
test_data += '</tr>';
});
$('#test').append(test_data);
});

Related

DataTables: How to display first column (ID) as hyperlink?

I'm trying to display my DataTables table with 3 columns (ID, Name, Date) showing values in my first column (ID) as URLs:
Edited as per #andrewjames request in comments:
<head>
<link rel='stylesheet' href='https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.css'>
<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script src='https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.js'></script>
<script src='https://cdn.datatables.net/scroller/2.0.3/js/dataTables.scroller.min.js'></script>
</head>
<body translate="no" >
<table id="example" class="display" cellspacing="0" width="75%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
</tr>
</tfoot>
</table>
<script id="rendered-js" >
$(document).ready(function () {
$('#example').DataTable({
"ajax": "url/to/data3.json",
"columns": [
{ "data": "ID" },
{ "data": "Name" },
{ "data": "Date" },
{
"data": "ID",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '<a href="https://test.com"'+ data +'>' + data + '</a>';
}
return data;
}
}
],
"order": [[ 2, "desc" ]],
"paging": true,
"deferRender": true,
"scrollY": 500,
"scrollCollapse": true,
"scroller": true,
"initComplete": function () {
this.api().row( 50000 ).scrollTo();
}
} );
} );
</script>
</body>
Error I'm getting: TypeError: undefined is not an object (evaluating 'n[m].style')
it relates to the following part of datatables.min.js:
else {
j = h(b).clone().css("visibility", "hidden").removeAttr("id");
j.find("tbody tr").remove();
var t = h("<tr/>").appendTo(j.find("tbody"));
j.find("thead, tfoot").remove();
j.append(h(a.nTHead).clone()).append(h(a.nTFoot).clone());
j.find("tfoot th, tfoot td").css("width", "");
n = ta(a, j.find("thead")[0]);
for (m = 0; m < i.length; m++)
p = c[i[m]], n[m].style.width = null !== p.sWidthOrig && "" !== p.sWidthOrig ? v(p.sWidthOrig) : "", p.sWidthOrig && f && h(n[m]).append(h("<div/>").css({
width: p.sWidthOrig,
margin: 0,
padding: 0,
border: 0,
height: 1
}));
Could someone tell me what am I doing wrong? thank you in advance!
Your DataTable defines 4 columns: ID, Name, Date, and the link.
It does not define any column title values, only the column data values - therefore it relies on the HTML table for these. However, there are only 3 columns defined. Add that 4th missing <tr> to both the <thead> and <tfoot> sections.
That should help to resolve the specific error you are getting.

How to.. Get the sum of the checked row for the the values "value" checked in AngularJS + HTML

​I'm a newbie when it comes to Angular, but, I really want to improve myself and learn, butttt now I have a big big problem.
I don't know how to get the sum for every row I checked ..only for the value entity.
Here you have a plunker with my try code.
https://plnkr.co/edit/iBdEtQU1gPrCSxXQ2yyW?p=preview
Thanks alot !
View HTML:
<table style="border: 1px solid black">
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Value</th>
</tr>
<td><b>Total</b></td>
</tr>
<tbody ng-repeat= "values in getSelected()">
<td></td>
<td>{{values.id}}</td>
<td>{{values.name}}</td>
<td>{{values.address}}</td>
<td>{{values.value}}</td>
</tbody>
</thead>
</table>
Controller code:
$scope.employees = [
{ id:"1", name: "A", address: "A1", value:10},
{ id:"2", name: "B", address: "A2",value:15 },
{ id:"3", name: "C", address: "A3",value:20},
{ id:"4", name: "D", address: "A4",value:25 },
{ id:"5", name: "E", address: "A5" ,value:30},
]
$scope.getSelected = function () {
var ar = $scope.employees.filter(function (value) {
if (value.checked == 1) {
return true;
} else {
return false;
}
});
console.log(ar);
return ar;
};
I'm assuming you want to get the sum of values of all selected rows. You may iterate over the array of selected items and sum up the values:
function() {
return $scope.getSelected().reduce((sum, item) => {
return sum + item.value;
}, 0);
}
Working example: https://plnkr.co/edit/TKDuKQB4rFO5U6w0bEBl?p=preview

angular ngTableParams from json

Having problem with creating table from json data.
Using Django + AngularJS
Data is not displayed.
tables.js
app.controller('tableCtrl', function(ngTableParams, tableData) {
var data = tableData
this.tableLatestContests = new ngTableParams({
page: 1,
count: 5,
}, {
total: data.length,
getData: function($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
}
});
services.js
app.service('tableData', [$resource, function($resource) {
this.data = $resouce('data/table.json', {}, {
query: {
method: 'GET',
isArray: true,
}
}
});
data/table.json
[
{"id": 1, "market": "name", "uid": "uid"},
{"id": 2, "market": "name2", "uid": "uid2"},
]
table.html (on app changed {{ & }} to // & // because of django syntax)
<div class="card-body card-padding" data-ng-controller="tableCtrl as tctrl">
<table ng-table="tctrl.tableLastestContests" class="table table-striped table-vmiddle">
<tr ng-repeat="w in $data">
<td data-title="'ID'"> // w.id // </td>
<td data-title="'MARKET'"> // w.market // </td>
<td data-title="'UID'"> // w.uid // </td>
</tr>
</table>
</div>
Any ideas how to read and display table with tada from json ?
You are misunderstanding something. $resource creates instance of service instead of getting data from the service. This is why you have service which is capable of getting data form json instead of data form json.
this.srv = $resouce('data/table.json', {}, {
query: {
method: 'GET',
isArray: true,
}
}
this.data = this.srv.query();
After successful loading you will get data in this.data.
Of course you can change last line to something like this:
var _self = this;
this.srv.query(function(response) {
_self.data = response;
});
In case you do not want to create service, you can do:
$http.get('data/table.json').then(function(response) {
_self.data = response.data;
});
My post does not include support for errors.
You can read more here:
https://docs.angularjs.org/api/ngResource/service/$resource
https://docs.angularjs.org/api/ng/service/$http
Also, you have error in view. Use data instead of $data in ng-repeat.

Save json data to file using AngularJS

I'm new to AngularJs. I'm having some trouble with this task.
I have the json file:
[{
"day": {"date": "12.01.2015", "dow": "monday", "in":"1"},
"lessons": [
{"time": "9.45 – 12.35", "title": "title", "teacher": "tname", "room": "3"},
... more lessons ...
]
},
... more days ...
]
My html file:
<table style="width: 100%;" class="table table-bordered">
<tbody ng-repeat="timetable in timetables" ng-if="ind==-1||ind==$index">
<tr ng-repeat="lesson in timetable.lessons">
<td rowspan="{{timetable.lessons.length}}" ng-if="!$index" style="vertical-align: top; text-align: left;">
{{timetable.day.date}}<br />
<div style="width: 100%; height: 100%; min-height: 100%; ">
<a href="#/list/{{timetable.day.in - 1}}" > {{timetable.day.dow}}</a></div>
</td>
<td>{{lesson.time}}</td>
<td>{{lesson.title}}</td>
<td>{{lesson.teacher}} <input type="textbox" ng-model="lesson.teacher"/></td>
<td>{{lesson.room}}</td>
</tr>
</tbody>
</table>
controllers.js:
angular.module('schedule.controllers', [])
.controller('ListLessonsCtrl', ['$scope', 'Schedule' , "$routeParams",
function ($scope, Schedule, $routeParams) {
if ($routeParams.ind === undefined) {
$scope.ind = -1;
} else {
$scope.ind = $routeParams.ind;
}
$scope.timetables = Schedule.query(); // get data form json file
$scope.save = function() {
Schedule.save($scope.timetables); // not works properly
};
}
])
... more code ...
And, finally, my services.js file:
angular.module('schedule.services', ['ngResource'])
.factory('Schedule', ['$resource', function($resource) {
return $resource('schedule/schedule.json', {}, {
query: {method: 'GET', isArray: true},
save: {method: 'POST'}
});
}]);
I need to get data from json file (done), update it on the page (know how to do it), and save updated data back to json file.
I tried to add function "save" to existing factory, but I don't know exactly, how to send data to it.
Could someone help me with it?
Thanks in advance!

How to create DataTable filled by JSON when number of columns is unknown

I have a table in my web-application, which is created like this:
<table id="mygrid">
<thead>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
window.oTable = $("#mygrid").dataTable({
"bServerSide": true,
"bSort": false,
"sAjaxSource": "#Url.Action("MyFunction", "Events")",
"fnServerParams": function(aoData) {
aoData.push({ name: "arg1", value: "#Model.arg1" });
},
"aoColumns": [
{ "mDataProp": "Column1" },
{ "mDataProp": "Column2" },
{ "mDataProp": "Column3" }
],
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bProcessing": false
});
I fill it with function that returns JSON result, like this:
ActionResult MyFunction(string arg1, ...)
{
List<string> someList = ...;
object array = eventsList.Select(str => new
{
Column1 = str + "1",
Column2 = str + "2",
Column3 = str + "3"
});
var result = new
{
sEcho = ...,
iTotalRecords = ...,
iTotalDisplayRecords = ...,
aaData = array
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Now I want to generate table dynamically, so I don't know the number of columns in design time. For example:
<table id="mygrid"><thead>
#{
foreach (string col in colNames)
<th>#col</th>
}
</thead></table>
Could you please advise how should I change my Javascript and C# code to fill the table in similar way? Is it possible? I can generate "mDataProp" lines in Javascript code like I generate columns, but how can I create JSON result in C# code?
Added:
I have solved the problem with controller. As I discovered, the List of Dictionaries is serialized to exactly the same JSON as the list of anonymous objects, so I wrote this:
for (int i = 0; i < n; ++i)
{
list.Add(new Dictionary<string, string>());
foreach (int colName in colNames) events[i][colName] = cellValue;
}
var result = new
{
...,
aaData = list
};
return Json(result, JsonRequestBehavior.AllowGet);
Now I have new question. I cannot generate "aoColumns" array using C# loop like I generated tags in HTML code. I tried like this:
"aoColumns": [
#{
for (int i = 0; i < n; ++i)
{
string colName = "Column" + i.ToString();
{ "mDataProp": "#colName" },
}
}
],
but it does not work. How can I do it?
DataTables does not allow to change column dynamically but you can get columns before data and load datatable on its callback function...
$.ajax('url/columns', function(data){
//write table header
var options =
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": getGridDataUrl,
"iDisplayLength": 10,
"aoColumns": //column settingssss
};
$('#myDataTable').dataTable(options);
});
I solved my problems. Generating JavaScript is easier that I thought. The problem was that when I generated the aoColumns array as the C# string and then assigned it to "aoColumns" property like this:
"aoColumns": [
#propertyStr
],
the compiler somehow hid the quotes and braces.
The right way was to do this:
"aoColumns": [
#Html.Raw(propertyStr)
],