populate js table with json data - javascript

can you please please help me with something? i'm trying to create a table based on the information i receive from an endpoint. i've managed to create the structure of the table.
<div class="available-movies-component">
<div class="color-code-wrapper">
<span class="title">Key</span>
</div>
<div class="table-wrapper">
</div>
</div>
const API = 'https://raw.githubusercontent.com/alex-cenusa/movies/master/movies.json';
async function getData() {
try {
let response = await fetch(API);
if (response.status == 200) {
let data = await response.json();
return data;
} else {
throw new Error(response.status);
}
} catch (error) {
console.log(error);
}
}
getData().then((data) => {
const KEY = data.data.key.forEach((key) => {
const LEGEND_WRAPPER = document.querySelector('.color-code-wrapper');
const UNIT_TYPE = key.type;
const KEY_BTN = document.createElement('button');
KEY_BTN.innerText = UNIT_TYPE;
const KEY_BTN_COLOR = key.color;
KEY_BTN.style.backgroundColor = KEY_BTN_COLOR;
LEGEND_WRAPPER.appendChild(KEY_BTN);
});
const TABLE_WRAPPER = document.querySelector('.table-wrapper');
let col = [];
for (let i = 0; i < data.data.movies.length; i++) {
for (let key in data.data.movies[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
const table = document.createElement('table');
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement('th'); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (let i = 0; i < data.data.movies.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = data.data.movies[i][col[j]];
}
}
TABLE_WRAPPER.appendChild(table);
});
and here is my jsfiddle https://jsfiddle.net/nopqxdvz/
what i need to do now, and i need some help with is to create a button inside every row corresponding to Type/Use column, with the name inside the object and for the background-color of the button to have the hex code inside the object. and for the Rental, to have a link with the href of the url provided if the url exists. right now i'm getting [object Object]
thanks in advance for every help i can get!

https://jsfiddle.net/cjr6sfpb/2/ here solution
Code i changed added button styling :
// added this mergeObjectValues function to handle.
let button_style= {
"Comedy" : "blue-button",
"Thriller":"pink-button",
"Alternative":"green-button",
"Documentary":"red-button"
}
function mergeObjectValues(key,obj,tablecell){
let merge_string = [];
let button;
for (let i = 0; i < obj.length; i++) {
if(merge_string.indexOf(obj[i][key]) == -1)
{
merge_string.push(obj[i][key]);
if (key == 'type'){
button = document.createElement('button');
button.classList.add(button_style[obj[i][key]]);
button.innerHTML = obj[i][key];
tablecell.append(button);
}
else{
merge_string.push(obj[i][key]);
tablecell.innerHTML = obj[i][key];
}
}
}
return tablecell;
}
const table = document.createElement('table');
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement('th'); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
let col_key ={
"Type/Use" : "type",
"Rental" : "name"
}
for (let i = 0; i < data.data.movies.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
var tablecontent = data.data.movies[i][col[j]];
console.log(col);
console.log(tablecontent instanceof Array);
if( tablecontent instanceof Array){
tabCell = mergeObjectValues(col_key[col[j]],tablecontent,tabCell);
}else{
tabCell.innerHTML = tablecontent;
}
}
}

Related

After submit remove old value and display new value when input changes

function createTable(event) { // event.preventDefault(); const input1 = document.getElementById("input1").value.split('#') const input2 = document.getElementById("input2").value.split('#') //input 1 const rows1 = parseInt(input1[0]); const columns1 = parseInt(input1[1]); let element1 = parseInt(input1[2]); //input 2 const rows2 = parseInt(input2[0]); const columns2 = parseInt(input2[1]); let element2 = parseInt(input2[2]); let table1 = document.getElementById('table1') let table2 = document.getElementById('table2') let table3 = document.getElementById('table3') table1.setAttribute('border', 2) table2.setAttribute('border', 2) table3.setAttribute('border', 2) //create table1 with html for (let i = 0; i < rows1; i++) { let tr = document.createElement("tr") for (let j = 0; j < columns1; j++) { let td = document.createElement("td") td.textContent = element1 tr.appendChild(td) element1++ } table1.appendChild(tr) } //create table2 with html for (let i = 0; i < rows2; i++) { let tr = document.createElement("tr") for (let j = 0; j < columns2; j++) { let td = document.createElement("td") td.textContent = element2 tr.appendChild(td) element2++ } table2.appendChild(tr) } if (rows1 == rows2 && columns1 == columns2) { for (i = 0; i < rows1; i++) { let tr = document.createElement("tr") for (j = 0; j < columns1; j++) { let td = document.createElement("td") td.textContent = table1.rows[i].cells[j].textContent * table2.rows[i].cells[j].textContent // debugger; console.log(td.textContent) tr.appendChild(td) } table3.appendChild(tr) } } else { table3.style.display = 'none' } }

cells/rows are inserted under the first column

I'm working on a real-time timetable for a school, for that I've an admin panel with a side "User verwalten" (manage users) where I manage the rights and permissions of the individual users. I want to create a table with the name and checkbox where you can mark the rights with a cross.
The data for this(all users and there permissions) are located on a webserver.
The Problem:
Now I have added the table-header and I want to add the users. But now with the table-header everything gets added in the first column and I dont know why. When I debugged, it is found that the cells are added in the right row but if I add the row it looks like this:
But i want it to look like this but with a table-header:
Here is the code for createTable()
function createTable(json){
var obj = JSON.parse(json);
var oldBody = document.getElementsByTagName('tbody')[0];
var body = document.createElement('tbody');
//if i add this header everything gets desroyed
//var header = document.getElementById("header").innerHTML = '<tr><th class="header"><h3>Name</h3></th><th class="header"><h3>Schüler verwalten</h3></th><th class="header"><h3>Benutzer verwalten</h3></th><th class="header"><h3>History anschauen</h3></th><th class="header"><h3>Home verwalten</h3></th></tr>';
for (var j = 0; j < obj.length; j++) {
var row = addRow(obj[j]);
row.classList.add('row');
//table.appendChild(body);
}
}
code foraddRow()
function addRow(val) {
var tr = document.createElement('tr');
for( var i = 0; i < 5; i++){
if(i==0){
var name = val.substr(0,(val.length)-9);
addCell(tr, null,name);
}else{
var rest = val.substr((val.length)-9, val.length);
var values = rest.split(";");
addCell(tr, values[i], name);
}
table.appendChild(tr);
}
return tr;
}
code for addCell()
function addCell(tr, val, name) {
var name;
var cell = document.createElement('input');
var value = "get";
if(val == null){
cell.classList.add("name")
cell.value = name;
cell.addEventListener("dblclick", function () {
cell.classList.remove('cell');
cell.classList.add('selected');
clearSelection();
});
}else if(val == 0){
cell.classList.add('checkbox');
cell.type = "checkbox";
cell.checked = false;
cell.addEventListener( 'change', function() {
value += getString();
getData(value);
});
}else if(val == 1){
cell.classList.add('checkbox');
cell.type = "checkbox";
cell.checked = true;
cell.addEventListener( 'change', function() {
value += getString();
getData(value);
});
}
tr.appendChild(cell);
}
I think you need to set a newStartIndex var.
Something like this is what I did. (If I understand correctly)
I realize this might not be exactly what you are asking but perhaps it points you in the right direction.
var ucfIndex = 2;
const ucfSelectedRowIndex = rows.indexOf(feedbackCandidates[x]) + ucfIndex;
var sheets = google.sheets({ version: 'v4' });
authorize(function () {
var request = {
spreadsheetId: 'yourSheetId',
valueInputOption: 'RAW',
resource: {
"data": [
{
"range": "N" + ucfSelectedRowIndex,
"majorDimension": "COLUMNS",
"values": [
[
true
],
]
},
],
},
auth,
};
sheets.spreadsheets.values.batchUpdate(request, function (err, response) {
if (err) {
console.error(err);
return;
}
else {
console.info(response);
console.log("Col Values updated");
};
});
});
Code for Add row
var table = document.getElementById("tbl");
for (var i = 0 ; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
row += table.rows[i].cells[j].innerHTML;
row += " | ";
}
alert(row);
}

JavaScript Json row undefined for TreeView

I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao

Gridview search filter with paging

function Search_Gridview(strKey, strGV) {
var strData = strKey.value.toLowerCase().split(" ");
var tblData = document.getElementById(strGV);
var rowData;
for (var i = 1; i < tblData.rows.length; i++) {
rowData = tblData.rows[i].innerHTML;
var styleDisplay = 'none';
for (var j = 0; j < strData.length; j++) {
if (rowData.toLowerCase().indexOf(strData[j]) >= 0)
styleDisplay = '';
else {
styleDisplay = 'none';
break;
}
}
tblData.rows[i].style.display = styleDisplay;
}
}
i have a gridview and i want to add search filter on it. This code works correctly but search just one page not all rows. How i make this, i discovered but i didn't solve this.

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Categories

Resources