Fill a table according to other cells with js - javascript

I'm trying to fill a html table according to the left cells of that table.
So this code below creates a table which is filled by variables :
<table id="myTable" ></table>
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8",
carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('myTable').find('td').each(function () {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
</script>
I've also tried to loop in the array but with no success :
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8", carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
arr2.forEach(function() {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
}
</script>
What I want is for every left cell to check if the right one have the same name in the array of object rightcell and print the carac accordingly.(N1 should be next to Name1 and so on).
Any idea ?
Thanks for the help.

Your code has a lot of errors like using arr2 / cell2 outside of their scopes, not using # for getting id etc. Take a look at the working code:
This works:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<table id="myTable"></table>
<script>
var rightcell = [{
name: "Name2",
carac: "N2"
}, {
name: "Name8",
carac: "N8"
}, {
name: "Name5",
carac: "N5"
}];
var rightCellMap = {};
for (var index = 0; index < rightcell.length; index++) {
rightCellMap[rightcell[index].name] = rightcell[index].carac;
}
arr2 = [
"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10"
];
for (var j = 0; j < 10; j++) {
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('#myTable').find('tr').each(function (index, element) {
var firstTd = $(element).find('td:first')[0];
var firstTdData = firstTd.innerHTML;
if (firstTdData != '' && rightCellMap[firstTdData]) {
firstTd.nextSibling.innerHTML = rightCellMap[firstTdData];
} else {
firstTd.nextSibling.innerHTML = "nothing"
}
})
</script>

Related

How can I create an HTML table from a JavaScript object?

I want to create an html table. It should have two columns and x amount of rows.
var row = 1;
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
var display = document.getElementById("device=table-body");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"]
cell2.innerHTML = test[0]["device"]
<table id="device=table-body"></table>
I tried the code above, but it's not displaying anything. Not sure where I'm going wrong. End goal is below:
device. || Task
----------------
deviceA || Task1
task2
----------------
deviceB || task1
As you can see, there's a console error:
The index provided (1) is greater than the number of rows in the table (0). Set your variable to 0.
var row = 0;
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
var display = document.getElementById("device=table-body");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"]
cell2.innerHTML = test[0]["device"]
<table id="device=table-body"></table>
do you have a row inside your table ? if no, replace your variable row value to 0 or -1.
const addRow = id => {
var test = [{
device: "deviceA",
tasks: ["task1", "task2", "task3", "task5"]
}]
// Get Table by name
var display = document.getElementById(id);
// Insert a row at the end of the table
var newRow = display.insertRow(-1);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
cell1.innerHTML = test[0]["device"];
cell2.innerHTML = test[0]["device"];
};
addRow("myTable");
td {
border: 1px solid black;
}
<table id="myTable">
</table>

While displaying its also print old Data from local storage

function addrow() {
debugger;
var person = [];
if (localStorage.person1 != null && localStorage.person1 !=undefined) {
var person = JSON.parse(localStorage.person1);
}
var name = document.getElementById('name').value;
var city = document.getElementById('city').value;
person.push({
pname: name,
pcity: city
});
localStorage.setItem('person1', JSON.stringify(person));
bind();
}
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
for (i = 0; i < per_list.length; i++ ) {
var table = document.getElementById('ptable');
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}
I have two fields name and city;Now, click on "add row" prints ok for first value, but afterwards it is printing both old and new value.. And, i want only new entry below the old input.. thanks in advance
You need to clear the table since you are showing all the elements in the .bind function.
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
// clear the table
var table = document.getElementById('ptable');
for (var i = 0, rows = table.rows.length; i < rows; i++) {
table.deleteRow(0)
}
// fill the table
for (i = 0; i < per_list.length; i++) {
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}

How to close child window and redirect the link in parent current window

I'm getting some json data from the services and bind those values in the table format in the child window. Click on link in the child window, should close child window and redirect the url in parent current window.
<html>
<head>
<title>sample</title>
<script type="text/javascript">
var childWindow;
function GenerateStudentsTable() {
var jsondata = {
"school": {
"students": [{
"studentId": "Test1",
"Name": "Message01"
},
{
"studentId": "Test2",
"Name": "Message2"
}, {
"studentId": "Test3",
"Name": "Message3"
}
],
"redirectURL" : "https://www.google.com/search"
}
}
var query = "students";
var table = document.createElement("TABLE");
table.border = "1";
var headerLabels = ["Id", "Name"]
var headerLabelsCount = headerLabels.length;
var row = table.insertRow(-1);
for (var i = 0; i < headerLabelsCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = headerLabels[i];
row.appendChild(headerCell);
}
var jsonLength = Object.keys(jsondata.school.students).length;
for (var i = 0; i < jsonLength; i++) {
row = table.insertRow(-1);
for (var j = 0; j < headerLabelsCount; j++) {
var cell = row.insertCell(-1);
if (j == 0) {
cell.innerHTML = '' + jsondata.school.students[i].studentId + '';
} else {
cell.innerHTML = '' + jsondata.school.students[i].Name + '';
}
}
}
childWindow = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
childWindow.document.body.innerHTML = table.outerHTML;
}
function redirectToParentWindow()
{
childWindow.close();
window.location.href =jsondata.school.redirectURL;
}
</script>
</head>
<body>
<input type="button" value="Generate Table" onclick="GenerateStudentsTable()" />
<hr />
<div id="dvTable">
</div>
</body>
</html>
I have no issues in the binding data in the child window but i'm not sure how to close the child window and redirect to link in parent window. Thanks in advance
Below code changes are working as expected.
<html>
<head>
<title>sample</title>
<script type="text/javascript">
var childWindow, redirectUrl;
function GenerateStudentsTable() {
var jsondata = {
"school": {
"students": [{
"studentId": "Test1",
"Name": "Message01"
},
{
"studentId": "Test2",
"Name": "Message2"
}, {
"studentId": "Test3",
"Name": "Message3"
}
],
"redirectURL": "https://www.google.com/search"
}
}
var query = "students";
var table = document.createElement("TABLE");
table.border = "1";
var headerLabels = ["Id", "Name"]
var headerLabelsCount = headerLabels.length;
var row = table.insertRow(-1);
for (var i = 0; i < headerLabelsCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = headerLabels[i];
row.appendChild(headerCell);
}
var jsonLength = Object.keys(jsondata.school.students).length;
for (var i = 0; i < jsonLength; i++) {
row = table.insertRow(-1);
for (var j = 0; j < headerLabelsCount; j++) {
var cell = row.insertCell(-1);
if (j == 0) {
cell.innerHTML = '' + jsondata.school.students[i].studentId + '';
} else {
cell.innerHTML = '' + jsondata.school.students[i].Name + '';
}
}
}
redirectUrl = jsondata.school.redirectURL.concat("?q=query");
childWindow = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
childWindow.document.body.innerHTML = table.outerHTML;
}
function redirectToParentWindow() {
childWindow.close();
window.location.href = redirectUrl;
}
</script>
</head>
<body>
<input type="button" value="Generate Table" onclick="GenerateStudentsTable()" />
<hr />
<div id="dvTable">
</div>
</body>
</html>

Adding data rows dynamically from a json object using javascript?

I have a json file in my website project, like this:
[
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
]
Here it is the sample data, It has 4 columns but i don't know that my json data which i will get, will have how many number of columns. I am trying to create a dynamic html table from this json data. This is the code i have write now:
<script>
$(document).ready(function () {
var jsonitems = [];
$.getJSON("json.json", function (data) {
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
above code is working, I am facing problem when i try to insert data rows, below is the code for that which is not working:
//Add the data rows.
//for (var i = 1; i < data.length; i++) {
// row = table.insertRow(-1);
// for (var j = 0; j < totalColumns; j++) {
// var cell = row.insertCell(-1);
// cell.innerHTML = customers[i][j];
// }
//}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
});
});
</script>
Please help me with that.
Thanks
The way you are accessing the cell data is wrong. For example, to access id of first object, you've to do data[0]["id"], instead your code tries to do data[0][0]. Working example of your code:
var data = [{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
// Add the data rows.
for (var i = 0; i < data.length; i++) {
row = table.insertRow(-1);
columnNames.forEach(function(columnName) {
var cell = row.insertCell(-1);
cell.innerHTML = data[i][columnName];
});
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
<div id="dvTable"></div>
Based on what I can interpret, you can just do this. Access each object inside the array, then use the keys to map your values.
But what you've written as your example code and your provided data seems different.
let data = [
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var table = document.getElementById("table");
for (let item of data) {
row = table.insertRow(-1);
for (let key in item) {
var cell = row.insertCell(-1);
cell.innerHTML = item[key];
}
}
<table id="table">
</table>

Make table using object

I'm making a table but using only Javascript. I did the table already and it shows right on console, but I can't make it visible on the page. I tried appendChild() and insertBefore() and it doesn't work, and also can't make the URL clickable.
Here is my code:
var companies = [
{
id: 1,
name: 'Google',
link: 'http://google.com/'
},
{
id: 2,
name: 'Microsoft',
link: 'http://microsoft.com/'
},
{
id: 3,
name: 'Apple',
link: 'http://apple.com'
}
];
var tbl = document.createElement('table');
var input = document.getElementById('input');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_link = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_link.textContent = "link";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_link);
thead.appendChild(tr_head);
for(var i = 0; i < companies.length; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_link = document.createElement("td");
// var id = companies[i].id;
// var name = companies[i].name;
// var link = companies[i].link;
td_id.textContent = companies[i].id;
td_name.textContent = companies[i].name;
td_link.textContent = companies[i].link;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_link);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
// input.appendChild(tbl);
Do you write the output to the document? Else it will just remain in the script.
Like this:
document.body.appendChild(tbl);
Not the best way, but it's a way...
var input = document.getElementById("input");
var rows = "";
for(var i = 0; i < companies.length; i++) {
rows += "<tr><td>"+companies[i].id+"</td>"
+ "<td><a href='"+companies[i].link+"'>"+companies[i].name+"</a></td></tr>"
}
var table = "<table>"+rows+"</table>";
input.innerHTML = table;

Categories

Resources