The following code I have tried but its not working. I want to deploy data according to row id into table dynamically.So in future if someone make changes into json file then data must be displayed into table's column according the json data.For Instance, if I make changes in my json file day from monday to Friday then data must be displayed into Friday column without making any changes into javascript code.
var makeSchedule=
{
"schedule" : [
{"fitnessClass": "One",
"sessionType": "Push Up",
"duration": 1,
"allocatedTime": {
"group" : "A",
"day" : "mon",
"location" : "Main Hall",
"time": "11"
},
"alternativeTimes":
[
{"group" : "B",
"day" : "tues",
"location" : "Main Hall2",
"time": "11"}
]
},
{"fitnessClass": "Two",
"sessionType": "Running",
"duration": 1,
"allocatedTime": {
"group" : "A",
"day" : "weds",
"location" : "Main Hall 3",
"time": "9"
},
"alternativeTimes":
[
{"group" : "B",
"day" : "thurs",
"location" : "Main Hall 4",
"time": "9"}
]
},
{"fitnessClass": "Three",
"sessionType": "Pull Ups",
"duration": 1,
"day" : "thurs",
"location" : "Main Hall 3",
"time": "15"
}
]
}
window.addEventListener("load",function(){
makeSchedule.schedule.forEach(booked => {
if(booked.allocatedTime.day==='thurs')
{
document.getElementsByClassName('s9').innerHTML = `${booked.sessionType}`;
}
});
});
<table>
<tbody>
<tr id="mon">
<td class="dayRowHead">Monday</td>
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="tues">
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="thurs">
<td class="s9"></td>
<td class="s10"></td>
</tr>
</tbody>
</table>
This line:
if(booked.allocatedTime==='thurs')
Looks like it should be:
if(booked.allocatedTime.day ==='thurs')
According to the object you have.
document.getElementsByClassName('s9').innerHTML = ${booked.sessionType};
Update
#utkanos has pointed out that document.getElementsByClassName('s9').innerHTML returns a nodeList and not an HTMLElement, which is another problem. A more complete code chunk would look like this:
var makeSchedule = {
"schedule": [{
"fitnessClass": "One",
"sessionType": "Push Up",
"duration": 1,
"allocatedTime": {
"group": "A",
"day": "mon",
"location": "Main Hall",
"time": "11"
},
"alternativeTimes": [{
"group": "B",
"day": "tues",
"location": "Main Hall2",
"time": "11"
}]
},
{
"fitnessClass": "Two",
"sessionType": "Running",
"duration": 1,
"allocatedTime": {
"group": "A",
"day": "weds",
"location": "Main Hall 3",
"time": "9"
},
"alternativeTimes": [{
"group": "B",
"day": "thurs",
"location": "Main Hall 4",
"time": "9"
}]
},
{
"fitnessClass": "Three",
"sessionType": "Pull Ups",
"duration": 1,
"day": "thurs",
"location": "Main Hall 3",
"time": "15"
}
]
}
window.addEventListener("load", function() {
makeSchedule.schedule.forEach(booked => {
if (booked.allocatedTime && booked.allocatedTime.day === 'mon') {
document.querySelectorAll('.s9').forEach(el => {
el.innerHTML = `${booked.sessionType}`;
})
}
});
});
<table>
<tbody>
<tr id="mon">
<td class="dayRowHead">Monday</td>
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="tues">
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="thurs">
<td class="s9"></td>
<td class="s10"></td>
</tr>
</tbody>
</table>
Note that I used querySelectorAll() instead of getElementsByClassName(), and looped through the results with forEach(). Finally, I changed "thurs" to "mon", since "thurs" is only in booked.alternativeTimes.day and booked.day in your example data. I would suggest making your data object more uniform in structure so that you don't have to use a lot of conditionals to access the right data in the future. You should always be able, for example, to expect the "day" value to appear in the same place in each booked object.
you need to search for the class in the parent element
var x = document.getElementById("thurs");
x.getElementsByClassName("s9")[0].innerHTML = `${booked.sessionType}`;
Related
I'm used to functional programming in Java and have just been trying my hand at JS recently. I am trying to stream through a Json output that looks like this:
{
"originatingRequest": {
"clientId": 1,
"simulationName": "Season 2020",
"teamRatings": [{
"teamId": 1,
"rating": 2.5
},
{
"teamId": 2,
"rating": 0.85
},
{
"teamId": 3,
"rating": 1.35
},
{
"teamId": 4,
"rating": 1.35
}
],
"simulationId": "7d49cb14-d99e-4315-bba3-077d114ab6fc"
},
"markets": [{
"name": "Winner",
"selections": [{
"name": "Manchester City",
"probability": "0.25"
},
{
"name": "Manchester United",
"probability": "0.25"
},
{
"name": "Liverpool",
"probability": "0.25"
},
{
"name": "Chelsea",
"probability": "0.25"
}
]
},
{
"name": "Top Two",
"selections": [{
"name": "Manchester City",
"probability": "0.95"
},
{
"name": "Manchester United",
"probability": "0.05"
},
{
"name": "Liverpool",
"probability": "0.95"
},
{
"name": "Chelsea",
"probability": "0.05"
}
]
}
],
"created": "2020-05-27T11:12:43.467644"
}
I am trying to render the Winner market probabilities with the name of the teams into a bootstrap table. So this means I have to iterate through the JSON output until I match the name Winner and then iterate through that filtered object.
However, I'm not aware of the Javascript equivalent of the stream function in Java. I do know a bit about option chaining. This was my attempt, using find:
function SimulationReport() {
return (
<Table>
<thead>
<th>Team Name</th>
<th>Win Probability</th>
</thead>
<tbody>
{simulationResult
.find(t => t.originatingRequest.markets.name === "Winner")
.selections.map(selection => (
<tr key="">
<td>{selection.name}</td>
<td>{selection.probability}</td>
</tr>
))}
</tbody>
</Table>
);
}
Unfortunately this is the error I got:
TypeError: _api_model_simulationResult__WEBPACK_IMPORTED_MODULE_2__.find is not a function
What do I have to do to render this table?
You can't use find on JSON object, it should be array.
You can do something like this :
// simulationResult is JSON
// simulationResult.markets is array, so you can use find on it
simulationResult.markets.find()
Assuming the object you posted is simulationResult, your JSX would look like:
simulationResult
.markets
.find(t => t.name === "Winner")
.selections.map(selection => (
<tr key="">
<td>{selection.name}</td>
<td>{selection.probability}</td>
</tr>
))
My Json data is :
[{
"objective": "My obj",
"score": 9,
"status": "active",
"quarter": "Q1",
"year": "2015",
"team": "A",
"owner_ids": [
"175323"
],
"key_results": [{
"result": "resut11",
"status": "Pending"
}, {
"result": "result12",
"status": "On time"
}]
}, {
"objective": "My second obj",
"score": 5,
"status": "active",
"quarter": "Q2",
"year": "2015",
"team": "B",
"owner_ids": [
"175223"
],
"key_results": [{
"result": "resut21",
"status": "Pending"
}, {
"result": "result22",
"status": "On time"
}]
}, {
"objective": "My third objective",
"score": 3,
"status": "active",
"quarter": "Q3",
"year": "2015",
"team": "C",
"owner_ids": [
"15323"
],
"key_results": [{
"result": "resut31",
"status": "Pending"
}, {
"result": "result12",
"status": "Pending"
}]
}, {
"objective": "My fourth objective",
"score": 3,
"status": "active",
"quarter": "Q2",
"year": "2015",
"team": "A",
"owner_ids": [
"17598"
],
"key_results": [{
"result": "resut41",
"status": "Pending"
}, {
"result": "result42",
"status": "On time"
}]
}, {
"objective": "My fifth objective",
"score": 5,
"status": "active",
"quarter": "Q3",
"year": "2016",
"team": "B",
"owner_ids": [
"13298"
],
"key_results": [{
"result": "resut51",
"status": "Pending"
}, {
"result": "result52",
"status": "On time"
}]
}, {
"objective": "My sixth objective",
"score": 7,
"status": "active",
"quarter": "Q4",
"year": "2015",
"team": "B",
"owner_ids": [
"1328"
],
"key_results": [{
"result": "resut61",
"status": "Pending"
}, {
"result": "result62",
"status": "On time"
}]
}, {
"objective": "My seventh objective",
"score": 7,
"status": "active",
"quarter": "Q3",
"year": "2015",
"team": "B",
"owner_ids": [
"1328"
],
"key_results": [{
"result": "resut71",
"status": "Pending"
}, {
"result": "result72",
"status": "On time"
}]
}]
In my view I am displaying the data in table as well as calculating the average of the final score.
I am able to display and average all the data, Now I need to filter teh data based on the year and then quarter.
View Page :
<h3>Overall Score: {{calculateAverage(xyz)}}</h3>
<tbody>
<tr ng-repeat="entries in xyz">
<td>{{$index + 1}} </td>
<td>{{entries.objective}}</td>
<td>{{entries.key_results[0].result}}</td>
<td ng-class="{'text-success': entries.key_results[0].status == 'Pending', 'text-danger': entries.key_results[0].status == 'On time' }">
{{entries.key_results[0].status}}
</td>
<td>{{entries.final_score}}</td>
<td>{{entries.owner_ids[0]}}</td>
<td>
<a class="btn btn-sm btn-success" ng-click="/#/mypage/{{entries.owner_ids[0]}}"> View It </a>
</td>
</tr>
</tbody>
controller:
$scope.xyz = myservice.query();
$scope.calculateAverage = function (MyData) {
//console.log(MyData);
var sum = 0;
for (var i = 0; i < MyData.length; i++) {
var sum = sum + MyData[i].final_score;
}
var avg = sum / (MyData.length);
//console.log(avg);
return avg.toFixed(2);
};
There are other displays based on this over all data.
I have Implemented the drop down box
<div class="col-lg-3">
<h4>Year:</h4>
<select class="form-control" id="sel1" style="max-width:150px; margin-top:19px">
<option>2015</option>
</select>
</div>
<div class="col-lg-3">
<h4>Quarter:</h4>
<select class="form-control" id="sel1" style="max-width:150px; margin-top:19px">
<option>Q3</option>
<options>Q4</options>
</select>
</div>
It should display the distinct year as well as distinct month and on selection can it filter the json data and can the rest of the view be changed which is based on this overall data depending of the selected value from drop down?
Like changing the quarter to Q3 or year to 2015, the display in table and the average also changes accordingly , there are many dependent in view page on the overall data, this filter is just introduced, I do not want to change the various functions if the data scope can be changed based on dropdown select, looking for approach to accomplish this?
You can use Angular's filters to filter your data. You can also store your filtered results in scope variable and your original data remains intact. You need to add models to the select elements you are using as filters as shown:
<div class="col-lg-3">
<h4>Year:</h4>
<select class="form-control" id="sel1" style="max-width:150px; margin-top:19px" ng-model="yearFilter">
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
</div>
<div class="col-lg-3">
<h4>Quarter:</h4>
<select class="form-control" id="sel1" style="max-width:150px; margin-top:19px" ng-model="quarterFilter">
<option value="Q3">Q3</option>
<option value="Q4">Q4</option>
</select>
</div>
The filters should be applied as shown:
<tr ng-repeat="entries in filteredObjects=(xyz|filter:{'year':yearFilter,'quarter':quarterFilter})">
Now you can use the filteredObjects scope variable anywhere in that controller and will contain only the filtered data, without changing your original data. Check out one simple example implementation based off of your code in this jsFiddle.
I am trying to convert data present in an HTML table into JSON link. I'm getting undefined values in object.
HTML code:
<table colspan="2" border="1">
<tr>
<th>Source</th>
<th>Destination</th
</tr>
<tr ng-repeat="col in MapCol">
<td>
<select ng-model="col.value" ng-init="col.value=MainData.headers[$index].header">
<option ng-selected="{{head.header == col.value}}" ng-repeat="head in MainData.headers">{{head.header}}
</option>
</select>
</td>
<td>{{col.ColName}}</td>
</tr>
</table>
<br/>
<button ng-click="map();">Map</button>
Controller code:
var app = angular.module("ShrTest", []);
app.controller("Test1", function ($scope) {
$scope.MainData = { "name": "1-06082015185338.txt", "headers": [{ "header": "Name" }, { "header": "Age" }, { "header": "Address" }], "records": [{ "Name": "Paul", "Age": "23", "Address": "1115 W Franklin" }, { "Name": "Bessy the Cow", "Age": "5", "Address": "Big Farm Way" }, { "Name": "Zeke", "Age": "45", "Address": "W Main St" }] };
$scope.MapCol = [{ "ColName": "Col1" }, { "ColName": "Col2" }, { "ColName": "Col3" }];
$scope.map=function(){
$scope.fields=[{"source":$scope.value,"destination":$scope.ColName}];
console.log(" $scope.fields..", $scope.fields);
}
});
JS
$scope.map=function(){
$scope.fields = [];
for(i in $scope.MapCol){
var obj = $scope.MapCol[i]; $scope.fields.push({"source":obj.value,"destination":obj.ColName})
}
console.log($scope.fields);
}
Here is Modified fiddle:
Demo Here
I hope this will help you.
I have created an application in angularjs with ngTable, The application is working fine but sorting is not working. My json structured is nested, but values are coming correctly with the table
Can anyone please tell me some solution for this
My code is as given below
JSFiddle
html
<div ng-controller="IndexCtrl">
<table border="1" ng-table="mytable">
<tbody ng-repeat="peop in peoples">
<tr ng-repeat="people in peop">
<td sortable="'id'" data-title="'Id'">{{people.id}}</td>
<td sortable="'desig'" data-title="'Desig'">{{people.desig}}</td>
<td sortable="'name'" data-title="'Name'">{{people.name}}</td>
<td sortable="'place'" data-title="'Place'">{{people.place}}</td>
</tr>
</tbody>
</table>
</div>
script
var app = angular.module('app', ['ngTable']);
app.controller('IndexCtrl', function ($scope, $filter, ngTableParams) {
$scope.peoples = {
"ime123": [{"id": 145,
"desig": "doctor",
"name": "Manu",
"place": "ABCD"
}],
"ime148": [{"id": 148,
"desig": "engineer",
"name": "John",
"place": "POLK"
},
{
"id": 150,
"desig": "scientist",
"name": "Mary",
"place": "USE"
}]
};
$scope.mytable = new ngTableParams({
sorting: {
name: 'desc'
}
}, {
getData: function($defer, params) {
$scope.peoples = $filter('orderBy')( $scope.peoples, params.orderBy());
$defer.resolve( $scope.peoples);
}
});
});
The way you work with nested array in ngtable is not suitable ,in your case you can make array one dim again and allow directive to groupping
html
<table border="1" ng-table="mytable">
<tbody ng-repeat="peop in $groups">
<tr ng-repeat="people in peop.data">
<td sortable="id" data-title="'Id'">{{people.id}}</td>
<td sortable="desig" data-title="'Desig'">{{people.desig}}</td>
<td sortable="name" data-title="'Name'">{{people.name}}</td>
<td sortable="place" data-title="'Place'">{{people.place}}</td>
</tr>
</tbody>
</table>
contoller
$scope.mytable = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'desc'
}
}, {
total: peoples.length,
groupBy:'group',
getData: function ($defer, params) {
peoples = $filter('orderBy')(peoples, params.orderBy());
$defer.resolve(peoples);
}
});
data
var peoples = [{
"id": 145,
"desig": "doctor",
"name": "Manu",
"place": "ABCD",
"group": "ime123" //for grouping
}, {
"id": 148,
"desig": "engineer",
"name": "John",
"place": "POLK",
"group": "ime148" //for grouping
}, {
"id": 150,
"desig": "scientist",
"name": "Mary",
"place": "USE",
"group": "ime148" //for grouping
}];
here almost working jsfiddle.
default desc not working yet (ver 0.3.1)
I am using the TreeTable plugin:
http://ludo.cubicphuse.nl/jquery-treetable/#examples
<table id="example-basic">
<thead>
<tr>
<th>Name</th> <th>Status</th> <th>id</th>
</tr>
</thead>
<tbody data-bind="foreach: TreeView">
<tr data-bind="attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}">
<td data-bind="text: Name"></td>
<td data-bind="text: Status"></td>
<td data-bind="text: id"></td>
</tr>
</tbody>
</table>
<button type="button" name="test" onclick="test()"></button>
The below works if I HardCode as is and the result is shown as a nicely formatted TreeView.
ko.applyBindings({ TreeView: [{ "id": "1", "Parentid": null, "Name": "test1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "test2", "Status": "OK" }] }
But, I am getting the value from the server(put the value obtained from server in "str" variable) and doing the binding as below:
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]',
json = JSON.stringify(eval("(" + str + ")")),
ko.applyBindings({ TreeView: json})
function reload() {
//ko.applyBindings({ TreeView: {} });
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }]'
json = JSON.parse(str),
ko.applyBindings({ TreeView: json})
I get the following error:
Error: Unable to parse bindings.
Message: ReferenceError: 'id' is undefined;
Bindings value: attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}
Can someone please help. Thanks!
The Json object returned had to be converted to type string and then parsed. This resolved the above issue
New Issue:
I was just playing around with the treetable plugin. I wish to reload the data from server on button click(or ajax call every 5 sec). The data is duplicated.
You are stringifying the JSON instead of parsing it, and using eval() when you don't need it. Instead, just use JSON.parse().
var str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]';
var json = JSON.parse(str);
ko.applyBindings({ TreeView: json });