Get elements from one class to another class in HTML Table - javascript

I need to loop through .mainheader class to .mainheader because i need header class row and values class row value for grouping
This is my html
<table id="t01" cellspacing="0" cellpadding="0" class="table" style="margin-top:20px">
<thead>
<tr>
<th class="sorting">Group_Main_ID</th>
<th class="sorting">Group_Sub_ID</th>
<th class="sorting">Item</th>
<th class="sorting">Instructions</th>
<th class="sorting">Decision_Request_Input</th>
<th class="sorting">Status</th>
<th class="sorting">Evidence_Info</th>
<th class="sorting">Evidence_Doc</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody id="editContents">
<tr id="1" class="mainheader " bgcolor="#000033">
<td id="nonEdit" class="th1 p_no" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header1</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
SubHeader1</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header1.2</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr id="1" class="mainheader " bgcolor="#000033">
<td id="nonEdit" class="th1 p_no" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header2</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
SubHeader2.1</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
</tbody>
</table>
My Javascript
var groupData = {};
var subGroupData = {};
var arr = [];
$('#t01 tbody tr.mainheader').each(function(i) {
var groupIdData ={};
groupIdData['id'] = $(this).attr('id');
groupIdData['name'] = $(this).find('td:eq(2)').text().trim()
groupIdData["action"]= 'Add/Edit/Delete'
//arr.push(garr)
groupData['group'] = groupIdData;
groupData['subgrps'] = [];
subGroupData = {};
subGroupData["action"]= 'Add/Edit/Delete'
subGroupData['id'] =$(this).next('.header').attr('id');
subGroupData['name']= $(this).next('.header').find('td:eq(2)').text().trim();
//arr.push(garr)
groupData['subgrps'].push(subGroupData)
subGroupData['items'] = [];
var items = [];
$(this).next('tr').each(function(){
if($(this).hasClass('values'))
{
var rowData = {};
$(this).find('td').each(function(i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
if(i == 0)
rowData["Action"]='Add/Edit/Delete'
if(i>1)
rowData[thh]=$(this).text().trim()
});
//arr.push(garr)
items.push(rowData)
}
else
return
});
//console.log('over')
}
subGroupData['items'].push(items);
groupData['subgrps'].push(subGroupData);
arr.push(groupData);
});
alert(JSON.stringify(arr)) ;
My Fiddle
https://jsfiddle.net/694kjj3o/
I am expecting JSON look like this
[
{
"group": {
"value": "Header1"
},
"subgrps": [
{
"name": {
"value": "SubHeader1.1"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
],
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
},
{
"name": {
"value": "SubHeader1.2"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
}
]
},
{
"group": {
"value": "Header2"
},
"subgrps": [
{
"name": {
"value": "Header2.1"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
}
]
}
]
I am unable loop it . Kindly guide me in this situation

Try
var arr = [];
$('#t01 tbody tr.mainheader').each(function (i) {
var $main = $(this),
main = {
"group": {
"value": $main.text().trim()
},
"subgrps": []
};
console.group($main.text().trim());
console.log(this);
$main.nextUntil('.mainheader', '.header').each(function () {
var $header = $(this),
header = {
"name": {
"value": $header.text().trim()
},
"items": []
};
console.group($header.text().trim());
console.log(this);
$header.nextUntil('.mainheader, .header', '.values').each(function (i) {
var $tr = $(this),
$tds = $tr.children(),
obj = {
"value": {
"Group_Main_ID": $tds.eq(0).text().trim(),
"Group_Sub_ID": $tds.eq(1).text().trim(),
"Item": $tds.eq(2).text().trim(),
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
};
console.group(i);
console.log(this);
header.items.push(obj);
console.groupEnd();
});
main.subgrps.push(header);
console.groupEnd();
});
arr.push(main);
console.groupEnd();
});
console.log(arr)
console.log(JSON.stringify(arr));
Demo: Fiddle
If you want to get dynamic key and values
var arr = [];
$('#t01 tbody tr.mainheader').each(function (i) {
var $main = $(this),
main = {
"group": {
"action":'Add/Edit/Delete',
"value": $main.text().trim()
},
"subgrps": []
};
//console.group($main.text().trim());
//console.log(this);
$main.nextUntil('.mainheader', '.header').each(function () {
var $header = $(this);
header = {
"name": {
"action":'Add/Edit/Delete',
"value": $header.text().trim()
},
"items": []
};
//console.group($header.text().trim());
//console.log(this);
$header.nextUntil('.mainheader, .header', '.values').each(function (i) {
var $tr = $(this);
obj = {};
obj.action = 'Add/Edit/Delete';
var sobj = {}
$tr.find('td').each(function (i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
sobj[thh] = $(this).text().trim()
});
obj.value = sobj;
//console.group(i);
//console.log(this);
header.items.push(obj);
//console.groupEnd();
});
main.subgrps.push(header);
//console.groupEnd();
});
arr.push(main);
//console.groupEnd();
});
//console.log(arr)
console.log(JSON.stringify(arr));
DEMO
https://jsfiddle.net/95nqr6op/6/

Your code is having extra closing curly bracket }.
I Updated the code. There are some errors I found on the console.
$('#t01 tbody tr.mainheader').each(function(i) {
var groupIdData = {};
groupIdData['id'] = $(this).attr('id');
groupIdData['name'] = $(this).find('td:eq(2)').text().trim()
groupIdData["action"] = 'Add/Edit/Delete'
//arr.push(garr)
groupData['group'] = groupIdData;
groupData['subgrps'] = [];
subGroupData = {};
subGroupData["action"] = 'Add/Edit/Delete'
subGroupData['id'] = $(this).next('.header').attr('id');
subGroupData['name'] = $(this).next('.header').find('td:eq(2)').text().trim();
//arr.push(garr)
groupData['subgrps'].push(subGroupData)
subGroupData['items'] = [];
var items = [];
$(this).next('tr').each(function() {
if ($(this).hasClass('values')) {
var rowData = {};
$(this).find('td').each(function(i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
if (i == 0)
rowData["Action"] = 'Add/Edit/Delete'
if (i > 1)
rowData[thh] = $(this).text().trim()
});
//arr.push(garr)
items.push(rowData)
} else
return
});
//console.log('over')
subGroupData['items'].push(items);
groupData['subgrps'].push(subGroupData);
arr.push(groupData);
});

Related

how to create/add a new table row with javascript alone

What Im trying to do:
Use peopleDropdown to add the new person to the person dropdown within createPerson
Use peopleTable to add a new table row within createPerson
main.js:
class Dropdown {
constructor(idSelector) {
this.idSelector = idSelector;}
getCurrentSelection() {
return $(this.idSelector).val();}
appendToDropdown(label, value) {
$(this.idSelector).append(`<option value=${value}>${label}</option>`);}
}
class Table {
constructor(idSelector) {
this.selector = idSelector;
}
appendRow(data) {
let tableRows = `
<td class="name-col"></td>
<td class="balance-col"></td>
<td class="consumed-col"></td>
`;
$(this.selector).append(`<tr id="">${tableRows}</tr>`);
}
modifyRow(/*define inputs*/) {}
}
const peopleDropdown = new Dropdown('#people-dropdown');
const peopleTable = new Table(`#person-table tbody`);
const allPeople = [];
const createPerson = () => {
let name = getNameInput();
allPeople.push(name);
//peopleDropDown code
//peopleTable code
}
I'm stuck on how to add the tables since my regular way of doing this would be using react as the framework. (which is not a option here)
Html:
<div id="creator-row">
<input id="name-input" placeholder="Name" />
<button onclick="createPerson()">Create Person</button>
</div>
<div id="consume-row">
<label for="person-list">Choose a person:</label>
<select name="person-list" id="people-dropdown"></select>
</div>
<table id="person-table">
<thead>
<tr class="header-row">
<th class="name-col">Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
This snippet only answers the question of how to add the rows to the table
const table = document.getElementById("person-table");
const tbody = table.querySelector("tbody");
const tr = document.getElementById("tr");
// some people
const people = [{
"name": "one",
"balance": 1,
"consumed": 1
},
{
"name": "two",
"balance": 2,
"consumed": 2
},
{
"name": "three",
"balance": 3,
"consumed": 3
},
];
// loop through the people and add them to the table
people.forEach(p => {
const newRow = tr.content.cloneNode(true);
const cells = newRow.querySelectorAll("td");
cells[0].textContent = p.name;
cells[1].textContent = p.balance;
cells[2].textContent = p.consumed;
tbody.appendChild(newRow);
});
td {
border: 1px solid #000;
}
<table id="person-table">
<thead>
<tr class="header-row">
<th class="name-col">Name</th>
<th class="balance-col">Balance</th>
<th class="consumed-col">Consumed</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- a template of the row -->
<template id="tr">
<tr>
<td class="name-col"></td>
<td class="balance-col"></td>
<td class="consumed-col"></td>
</tr>
</template>

Delete table content from id

I have a function to generate rows from Javascript, and a function to clear it, but when delete I can't use the function to create again because it removes all.
I need to remove only the content and don't find how.
function myFunction() {
var stock = new Array()
stock[0] = new Array("Cars", "1", "2", "3", "4", "5")
stock[1] = new Array("Veggies", "11", "22", "33", "44", "55")
stock[2] = new Array("Colors", "111", "222", "333", "444", "555")
stock[3] = new Array("Numbers", "1111", "2222", "3333", "4444", "55555")
stock[4] = new Array("Requests", "28.625", "68.625", "22", "22", "22")
var table = document.getElementById("tableBody");
for (i = 0; i < stock.length; i++) {
var row = table.insertRow(i);
for (j = 0; j < stock[i].length; j++) {
var cell = row.insertCell(j);
cell.innerHTML = stock[i][j];
}
}
}
function removeTable(id) {
var tbl = document.getElementById(id);
if (tbl) tbl.parentElement.removeChild(tbl);
}
table,
td {
border: 1px solid black;
}
<table id="tablaPass" width="100%" height="20" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr height="40px">
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Marca</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Modelo</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Version</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Puertas</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Potencia</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">F. Lanzamiento</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<input type="button" onclick="removeTable('tableBody');" value="Remove!" />
Clear just the rows:
var tbody = document.getElementById('tableBody');
var rows = tbody.querySelectorAll('tr');
for (i = 0; i < rows.length; i++)
tbody.removeChild(rows[i]);
function myFunction() {
var stock = []
stock[0] = ["Cars", "1", "2", "3", "4", "5"]
stock[1] = ["Veggies", "11", "22", "33", "44", "55"]
stock[2] = ["Colors", "111", "222", "333", "444", "555"]
stock[3] = ["Numbers", "1111", "2222", "3333", "4444", "55555"]
stock[4] = ["Requests", "28.625", "68.625", "22", "22", "22"]
var table = document.getElementById("tableBody");
for (i = 0; i < stock.length; i++) {
var row = table.insertRow(i);
for (j = 0; j < stock[i].length; j++) {
var cell = row.insertCell(j);
cell.innerHTML = stock[i][j];
}
}
}
function removeTable(id) {
// Get the table body
var tbody = document.getElementById(id);
// Find and remove all the <tr> in the body
var rows = tbody.querySelectorAll('tr');
for (i = 0; i < rows.length; i++)
tbody.removeChild(rows[i]);
}
document.getElementById('tryit').addEventListener('click', myFunction);
document.getElementById('removeit').addEventListener('click', function() {
removeTable('tableBody');
});
table,
td {
border: 1px solid black;
}
th {
padding: 10px;
}
<table id="tablaPass" width="100%" height="20" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr height="40px">
<th valign="middle">Marca</th>
<th valign="middle">Modelo</th>
<th valign="middle">Version</th>
<th valign="middle">Puertas</th>
<th valign="middle">Potencia</th>
<th valign="middle">F. Lanzamiento</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<br>
<button id="tryit">Try it</button>
<button id="removeit">Remove</button>
Check this out, this is another way to do it
function removeTable(id)
{
var tbl = document.getElementById(id);
tbl.innerHTML = ''
}

Build array with all elements with specific class using JS

I have a table with multiple rows. I need to get the text from specific rows and build an array which I can pass on and access later. I created a jsfiddle with the code that I am using:
https://jsfiddle.net/h6x2sqk2/3/
The problem is that everything is doubled:
[
{
"drdsc":"DSCDS0101101",
"bkpsets":[
{
"backpset":"Backup1",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup2",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup3",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup4",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
}
]
},
{
"drdsc":"DSCDS0202202",
"bkpsets":[
{
"backpset":"Backup1",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup2",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup3",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup4",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
}
]
}
]
Result that I need is:
[
{
"drdsc":"DSCDS0101101",
"bkpsets":[
{
"backpset":"Backup1",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup2",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
},
{
"backpset":"Backup3",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
}
]
},
{
"drdsc":"DSCDS0202202",
"bkpsets":[
{
"backpset":"Backup4",
"srvrolenotes":"",
"setsize1notes":"",
"setsize2notes":""
}
]
}
]
Try my suggestion here. What i did is to read from one backup till the other what you have in the tr sections
working example
$( document ).ready(function() {
var dscarray = $('.bkpsrvdsc').map(function() {
var $dsclient = $(this);
var $rows = $dsclient.closest('tr').nextUntil('tr:has(.drbkpsetdsc)');
var drbkparray = $dsclient.closest('tr').nextUntil('tr:has(.bkpsrvdsc)').find('.drbkpset').parent().map(function() {
var $backuppset = $(this);
var obj = { backpset: $backuppset.text() };
var $rows = $backuppset.closest('tr').nextUntil('tr:has(.drbkpset)');
obj['srvrolenotes'] = $rows.find('.srvrolenotes').val();
obj['setsize1notes'] = $rows.find('.setsize1notes').val();
obj['setsize2notes'] = $rows.find('.setsize2notes').val();
return obj;
}).get();
var obj = { drdsc: $dsclient.text(), bkpsets: drbkparray };
return obj;
}).get();
console.log(dscarray);
});
Your $rows get more then one row because .nextUntil('tr:has(.drbkpsetdsc)') runs through the complete table and not until the next .bkpsrvdsc
It could be easier if you put a table into a td.bkpsrvdsc
$(document).ready(function() {
var dscarray = $('.bkpsrvdsc').map(function() {
var bkpsrvdsc = $(this);
return {
name: $(this).find('tr:first-child > td').text(),
contents: bkpsrvdsc.find('.drbkpset').map(function() {
return {
backpset: $(this).text(),
srvrolenotes: $(this).next('tr').find('.srvrolenotes').text(),
}
})
}
});
console.log(dscarray);
});
.bkpsrvdsc table {
width: 100%;
}
table th,
table td {
width: 33.3333%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width: 600px;">
<thead>
<tr>
<th>DSC#</th>
<th>Check</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3" class="bkpsrvdsc">
<table>
<tbody>
<tr>
<td>DSCDS0101101</td>
<td></td>
<td></td>
</tr>
<tr>
<td> </td>
<td colspan="2" class="drbkpset">Backup1</td>
</tr>
<tr>
<td> </td>
<td>Server role</td>
<td><textarea data-autoresize rows="1" placeholder="Type notes here..." class="srvrolenotes"></textarea></td>
</tr>
<tr>
<td> </td>
<td colspan="2" class="drbkpset">Backup2</td>
</tr>
<tr>
<td> </td>
<td>Server role</td>
<td><textarea data-autoresize rows="1" placeholder="Type notes here..." class="srvrolenotes"></textarea></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td colspan="3" class="bkpsrvdsc">
<table>
<tbody>
<tr>
<td>DSCDS0202202</td>
<td></td>
<td></td>
</tr>
<tr>
<td> </td>
<td colspan="2" class="drbkpset">Backup4</td>
</tr>
<tr>
<td> </td>
<td>Server role</td>
<td><textarea data-autoresize rows="1" placeholder="Type notes here..." class="srvrolenotes"></textarea></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

Angular ng-repeat not rendering data correctly

I was trying to make a table from json structure but not getting it to render properly.
Output is not shown properly for the first two cells; Partial is empty and it is filling the only last one. Please refer below image
controller.js
.controller('wController', function($scope, $http) {
console.log('i m in ctrl 3');
$http({
method: "GET",
url: "http://custom.url.ch:3021/routepath",
headers: {
'Authorization': 'Basic Ydaeq2FwaQw1='
}
// headers : {"Authorization": "Basic " + auth}
}).then(function(response) {
console.log("yoyo", JSON.stringify(response));
$scope.data = response.data;
}, function(response) {
console.log("oaapop" + JSON.stringify(response));
});
});
// index.html
<div class="table-responsive" ng-controller="woController">
<table class="table table-condensed" border="1">
<thead>
<tr>
<th>Sites</th>
<th ng-repeat="worstData in data">
<center>{{$index+1}}</center>
</th>
<!-- <th><center>2</center></th> -->
<!-- <th><center>3</center></th> -->
<!-- <th><center>4</center></th> -->
<!-- <th><center>5</center></th> -->
</tr>
</thead>
<!-- <tbody> -->
<tbody>
<tr>
<td> PartialSite</td>
<td ng-repeat="worstData in data">{{$index}} {{[worstData[0][$index].PartialSite]}}</td>
</tr>
<tr>
<td>FailSite</td>
<td> </td>
<td></td>
<td> </td>
</tr>
<tr>
<td> Jobs mn</td>
<td> </td>
<td></td>
<td> </td>
</tr>
<tr>
<td>Largest Points</td>
<td> </td>
<td></td>
<td> </td>
</tr>
</tbody>
</table>
</div>
// JSON structure to make table structure
{
"data": {
"statusCode": 200,
"message": "Getting Data",
"data": [
[{
"PartialSite": "LRS",
"Partial": 2
}, {
"PartialSite": "Sooking",
"Partial": 1
}, {
"PartialSite": "Late",
"Partial": 1
}],
[{
"FailSite": "Sotelia",
"fail": 2
}, {
"FailSite": "Pccor",
"fail": 1
}, {
"FailSite": "PccroHotels",
"fail": 0
}],
[{
"ExecSite": "Sotelia",
"time": 240
}, {
"ExecSite": "Late",
"time": 240
}, {
"ExecSite": "Pccor",
"time": 120
}],
[{
"DataSite": "LRS",
"totalDP": 16
}, {
"DataSite": "Sooking",
"totalDP": 14
}, {
"DataSite": "Pccor",
"totalDP": 12
}]
]
},
"status": 200,
"config": {
"method": "GET",
"transformRequest": [null],
"transformResponse": [null],
"url": "http://custom.url.ch:3021/routepath",
"headers": {
"Authorization": "Basic Ydaeq2FwaQw1=",
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "OK"
}
Is this what you are looking for - https://plnkr.co/edit/aMYrwNPHCkGnxftZgke4?p=preview
<body data-ng-controller="sampleCtrl as ctrl">
<table class="table table-condensed" border ="1" >
<thead >
<tr>
<th>Sites</th>
<th ng-repeat="worstData in ctrl.data"><center>{{$index+1}}</center></th>
<!-- <th><center>2</center></th> -->
<!-- <th><center>3</center></th> -->
<!-- <th><center>4</center></th> -->
<!-- <th><center>5</center></th> -->
</tr>
</thead>
<!-- <tbody> -->
<tbody >
<tr >
<td > PartialSite</td>
<td ng-repeat="worstData in ctrl.data[0]">{{$index}} {{worstData.PartialSite}}</td>
</tr>
<tr>
<td>FailSite</td>
<td ng-repeat="worstData in ctrl.data[1]">{{$index}} {{worstData.FailSite}}</td>
</tr>
<tr>
<td> Jobs mn</td>
<td ng-repeat="worstData in ctrl.data[2]">{{$index}} {{worstData.time}}</td>
</tr>
<tr>
<td>Largest Points</td>
<td ng-repeat="worstData in ctrl.data[3]">{{$index}} {{worstData.totalDP}}</td>
</tr>
</tbody>
</table>
</body>
Answer is already got by some contributor named #Developer. I am just sharing the right code with you to fix this type of problem.
//index.html
<table class="table table-condensed" border ="1" >
<thead >
<tr>
<th>Sites</th>
<th ng-repeat="worstData in getHeaders(data[0].length) track by $index"><center>{{$index+1}}</center></th>
<!-- <th><center>2</center></th> -->
<!-- <th><center>3</center></th> -->
<!-- <th><center>4</center></th> -->
<!-- <th><center>5</center></th> -->
</tr>
</thead>
<!-- <tbody> -->
<tbody >
<tr >
<td > PartialSite</td>
<td ng-repeat="worstData in data[0]">{{$index}} {{worstData.PartialSite}}</td>
</tr>
<tr>
<td>FailSite</td>
<td ng-repeat="worstData in data[1]">{{$index}} {{worstData.FailSite}}</td>
</tr>
<tr>
<td> Jobs mn</td>
<td ng-repeat="worstData in data[2]">{{$index}} {{worstData.time}}</td>
</tr>
<tr>
<td>Largest Points</td>
<td ng-repeat="worstData in data[3]">{{$index}} {{worstData.totalDP}}</td>
</tr>
</tbody>
</table>
//script.js
angular.module("app", [])
.controller("sampleCtrl", function($scope) {
//var _this = this;
$scope.data = [
[{
"PartialSite": "LRS",
"Partial": 2
}, {
"PartialSite": "Sooking",
"Partial": 1
}, {
"PartialSite": "Late",
"Partial": 1
}],
[{
"FailSite": "Sotelia",
"fail": 2
}, {
"FailSite": "Pccor",
"fail": 1
}, {
"FailSite": "PccroHotels",
"fail": 0
}],
[{
"ExecSite": "Sotelia",
"time": 240
}, {
"ExecSite": "Late",
"time": 240
}, {
"ExecSite": "Pccor",
"time": 120
}],
[{
"DataSite": "LRS",
"totalDP": 16
}, {
"DataSite": "Sooking",
"totalDP": 14
}, {
"DataSite": "Pccor",
"totalDP": 12
}]
];
$scope.getHeaders = function(index) {
return new Array(index);
};
});

How to hide table column if all json value is null for any property using angular js

Plunker sample
How to hide table column if all json value is null for any property
using angular js
index.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.isArray = angular.isArray;
$scope.data = [{
"Id": null,
"Title": "US",
"Description": "English - United States",
"Values": [{
"Id": 100,
"LanId": 1,
"KeyId": 59,
"Value": "Save"
}]
}, {
"Id": null,
"Title": "MX",
"Description": "test",
"Values": [{
"Id": 100,
"LanId": 1,
"KeyId": 59,
"Value": "Save"
}]
}, {
"Id": null,
"Title": "SE",
"Description": "Swedish - Sweden",
"Values": [{
"Id": 100,
"LanId": 1,
"KeyId": 59,
"Value": "Save"
}]
}]
$scope.cols = Object.keys($scope.data[0]);
$scope.notSorted = function(obj) {
if (!obj) {
return [];
}
return Object.keys(obj);
}
});
index.html
<table border=1 style="margin-top: 0px !important;">
<thead>
<tr>
<th ng-repeat="(k,v) in data[0]">{{k}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td ng-repeat="(prop, value) in item" ng-init="isArr = isArray(value)">
<table ng-if="isArr" border=1>
<thead>
<tr>
<td>
<button ng-click="expanded = !expanded" expand>
<span ng-bind="expanded ? '-' : '+'"></span>
</button>
</td>
</tr>
<tr>
<th ng-repeat="(sh, sv) in value[0]">{{sh}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="sub in value" ng-show="expanded">
<td ng-repeat="(sk, sv) in sub">{{sv}}</td>
</tr>
</tbody>
</table>
<span ng-if="!isArr">{{value}}</span>
</td>
</tr>
</tbody>
</table>
You can filter out columns that have only null values with:
JavaScript
$scope.cols = Object.keys($scope.data[0]).filter(function(col) {
return $scope.data.some(function(item) {
return item[col] !== null;
});
});
and check in template if this column should be rendered:
HTML
<table border=1 style="margin-top: 0px !important;">
<thead>
<tr>
<!-- Iterate over non-null columns -->
<th ng-repeat="col in cols">{{col}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<!-- Use ngIf to hide redundant column -->
<td ng-if="cols.indexOf(prop)>=0" ng-repeat="(prop, value) in item" ng-init="isArr = isArray(value)" >
...
Plunker
http://plnkr.co/edit/PIbfvX6xvX5eUhYtRBWS?p=preview
So the id is null for every element in the array, then do
<th ng-repeat="(k,v) in data[0]" ng-show="v">{{k}}</th>
and
<td ng-repeat="(prop, value) in item" ng-init="isArr = isArray(value)" ng-show="value">
plnkr: http://plnkr.co/edit/rra778?p=preview
You need to make use of the cols property you defined in your $scope, but you also need to make sure its correct and responsive. You do that like this:
var colsFromData = function(data) {
var activeCols = {};
data.forEach(function(o) {
Object.keys(o).forEach(function(k) {
if(null == o[k])
return;
activeCols[k] = 1;
})
});
return Object.keys(activeCols);
}
$scope.cols = colsFromData($scope.data);
$scope.$watchCollection('data', colsFromData);
Then in your template, to use the now correct cols array:
...
<thead>
<tr>
<th ng-repeat="k in cols">{{k}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td ng-repeat="(prop, value) in item" ng-init="isArr = isArray(value)" ng-if="cols.indexOf(prop) >= 0">
...
And the updated plunker

Categories

Resources