How to put data into HTML table using javascript - javascript

Html file:
<body>
<table id="tblUser"></table>
</body>
Javascript :
var userName="Tom";
var age= "21";
//now to put these data into a table
Now, how to put the data inside Javascript into table so that it looks like this
Name - Age
Tom 21

You should use createElement() and appendChild(), check example bellow.
Hope this helps.
var table = document.getElementById('tblUser');
var userName="Tom";
var age= "21";
var tr = document.createElement('tr');
var td_1 = document.createElement('td');
var td_2 = document.createElement('td');
var text_1 = document.createTextNode('Name');
var text_2 = document.createTextNode('Age');
td_1.appendChild(text_1);
td_2.appendChild(text_2);
tr.appendChild(td_1);
tr.appendChild(td_2);
table.appendChild(tr);
var tr_2 = document.createElement('tr');
var td_3 = document.createElement('td');
var td_4 = document.createElement('td');
var text_3 = document.createTextNode(userName);
var text_4 = document.createTextNode(age);
td_3.appendChild(text_3);
td_4.appendChild(text_4);
tr_2.appendChild(td_3);
tr_2.appendChild(td_4);
table.appendChild(tr_2);
document.body.appendChild(table);
<table id="tblUser" border=1></table>

Related

Creating a table with multiple rows and column

I want to create a table with 4 rows with 3 columns, I am doing this way but with this code I am not getting anything. What I am doing wrong here?
let cell = ["a","b","c","x"];
let cell1 = ["d","e","f","y"];
let cell2 = ["g","h","i","z"];
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
for(let i=0; i< 3; i++){
var y = document.createElement("TR");
y.setAttribute("id", myTr[i])
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode(cell[i]);
var z1 = document.createElement("TD");
var s = document.createTextNode(cell1[i]);
var z2 = document.createElement("TD");
var r = document.createTextNode(cell2[i]);
z.appendChild(t);
z1.appendChild(s);
z2.appendChild(r);
document.getElementById(myTr[i]).appendChild(z);
document.getElementById(myTr[i]).appendChild(z1)
document.getElementById(myTr[i]).appendChild(z2)
}
}
<button onclick="myFunction()">Create</button>
After defining myTr it seems to work. And - like Carsten Løvbo Andersen already mentioned - your for loop needs to run through all elements of the given cells. I replaced your 3 with cell1.length.
let cell = ["a","b","c","x"];
let cell1 = ["d","e","f","y"];
let cell2 = ["g","h","i","z"];
const myTr=["a","b","c","d"];
function cmFunction(arr){
const transp=arr[0].map(a=>Array());
arr.forEach((ar,i)=>ar.forEach((a,j)=>transp[j][i]=a))
document.body.innerHTML+='<table class="myTable"><tbody>'
+transp.map((r,i)=>'<tr class="'+myTr[i]+'"><td>'+r.join("</td><td>")+"</td></tr>").join("\n")
+'</tbody></table>';
}
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
for(let i=0; i< cell1.length; i++){
var y = document.createElement("TR");
y.setAttribute("id", myTr[i])
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode(cell[i]);
var z1 = document.createElement("TD");
var s = document.createTextNode(cell1[i]);
var z2 = document.createElement("TD");
var r = document.createTextNode(cell2[i]);
z.appendChild(t);
z1.appendChild(s);
z2.appendChild(r);
document.getElementById(myTr[i]).appendChild(z);
document.getElementById(myTr[i]).appendChild(z1)
document.getElementById(myTr[i]).appendChild(z2)
}
}
<button onclick="myFunction()">Create</button>
<button onclick="cmFunction([cell,cell1,cell2])">CreateNew</button>
I edited the script in order to show you that the whole thing can be done in a much simpler way. In my version cmFunction() I replaced the id attributes by class ones as this will allow for repetitions (if the "create" is clicked repeatedly).

How can I put another text in a cell by using JavaScript?

I would like to put the array price in the same cell of the array antipasti. I've tried too but I substituted the text. I would like to have all of two arrays in the same cell.
I didn't know how to do that. Can someone pls tell me how? Thank you so much
Here is the image: https://i.stack.imgur.com/qwOkj.png
function generateTableAntipasti() {
//Build an array containing Customer records.
var antipasti = new Array();
antipasti.push(["Antipasti"]);
antipasti.push(["Patatine"]);
antipasti.push(["Kellogs"]);
antipasti.push(["Ciao"]);
antipasti.push(["Hello"]);
antipasti.push(["Bye"]);
var price = new Array();
price.push(["5,00$"]);
price.push(["5,00$"]);
price.push(["5,00$"]);
price.push(["5,00$"]);
price.push(["5,00$"]);
price.push(["5,00$"]);
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Antipasti";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < antipasti.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = antipasti[i];
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
All the above points put together and shortened a little bit ...
function generateTableAntipasti() {
//Build an array containing Customer records.
var antipasti = ["Antipasti","Patatine","Kellogs","Ciao","Hello","Bye"],
price = ["5,00$","5,00$","5,00$","5,00$","5,00$","5,00$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Antipasti";
table.cellSpacing = 8;
//Add the data rows.
antipasti.forEach((a,i)=>table.insertRow(-1).insertCell(-1).innerHTML = a +'<br>'+price[i]);
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableAntipasti()
<div id="dvTable"></div>

Unable to align the table rows with header after appendchild

I'm trying to append the rows and header to an HTML table element using onclick event of button defined in HTML document. Although it successfully adds the header and rows, it fails to align the first element of the row with the header, and the page renders the table in a format like this :
Below is the JavaScript method for updating/adding records to table by appending rows and a header:
function updateTable(){
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
var header = document.createElement("th");
var usernode = document.createElement("td");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
header.appendChild(usernode);
var enode = document.createElement("td");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
header.appendChild(enode);
var pnode = document.createElement("td");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
header.appendChild(pnode);
var lnode = document.createElement("td");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
header.appendChild(lnode);
var onode = document.createElement("td");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
header.appendChild(onode);
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
if(document.getElementById("t").querySelector("th")==null){
document.getElementById("t").appendChild(header);
}
document.getElementById("t").appendChild(noder);
clear();
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="form.js"></script>
<p id="test"></p>
<div id="userdiv">
<input type="text" placeholder="Username" id="uname">
</div>
<div id="maildiv">
<input type="text" placeholder="Email" id="email">
</div>
<div id="passdiv">
<input type="text" placeholder="Password" id="pass">
</div>
<div id="locdiv">
<input type="text" placeholder="Location" id="loc">
</div>
<div id="orgdiv">
<input type="text" placeholder="Organization" id="org">
</div>
<div id="gen">
<input type="radio"/> Male
<input type="radio"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
You are using the wrong element for the header.
"TH" is the equivalent for "TD", it's a cell, it goes inside a "TR".
You are adding TDs inside a TH, you actually need to add THs inside a TR. So change your createdElement('th') with createElement('tr') and the createElement('td') with createElement('th').
I'd also recommend you to use THEAD and TBODY tags inside your table.
Getting one bug, showing first row rendered adjacent to the header row..
enter image description here
Revised code :
function updateTable(){
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
var noder = document.createElement("tr");
if(i==0){
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
noder.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
noder.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
noder.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
noder.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
noder.appendChild(onode);
}
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
/*if(document.getElementById("t").querySelector("th")==null){
document.getElementById("t").appendChild(header);
}*/
document.getElementById("t").appendChild(noder);
clear();
}

Dynamically creating a table

I'm trying to create a table dynamically using JavaScript. So far i'm trying to understand what am i doing wrong. At first i'm making a table element and then i set id for that element. After that i'm looping through rows and as i do that, i create new columns in each new row. The problem which i'm having is that it stops making only 1st row. Can someone point out mistake im making?
var x = document.createElement("TABLE");
x.setAttribute("id", "newTable");
document.body.appendChild(x);
for (i=1;i<5;i++){
var y = document.createElement("TR");
y.setAttribute("id", "newTr");
document.getElementById("newTable").appendChild(y);
for (j=1;i<10;i++){
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("newTr").appendChild(z);
}
}
var x = document.createElement("TABLE");
x.setAttribute("id", "newTable");
document.body.appendChild(x);
for (i=1;i<5;i++){
var y = document.createElement("TR");
y.setAttribute("id", "newTr"+i);
document.getElementById("newTable").appendChild(y);
for (j=1;j<10;j++){
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("newTr" +i).appendChild(z);
}
}
i changed your second for-loop from i to j and i made the td-element id unique.
I think you will find that you mixed up jand i
for (j=1;i<10;i++){
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("newTr").appendChild(z);
}
try
for (i=1;i<10;i++){ //j here changed to i;
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("newTr").appendChild(z);
}

Adding class name or id to Table with JS

Suppose this code to create a table with plain JavaScript using DOM (Fiddle):
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
How can I add a class name or an id to its cells?
For example I want to be able to modify cells after their creation, so I want just :
table.getElementsByClassName("class").style.font-weight: "bold";
Use HTML DOM setAttribute() Method to add attributes to an element, like following :
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute('class', 'className');
td2.setAttribute('class', 'className');
Hope this helps.
Do:
table.setAttribute("id", "myId");
Read up: MDN Element.setAttribute()
Use the same function to set class, just like #Zakaria mentioned.

Categories

Resources