Some misunderstanding with creating dynamic table in JavaScript - javascript

I try to create dynamic table using JavaScript, the table contains two columns first name and family name.
Here is the JavaScropt code:
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement("thead");
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
var familyNameTxt = document.createTextNode("Family Name");
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'))
tr.cells[1].appendChild(document.createTextNode('McDowell'))
table.appendChild(tr);
}
tablearea.appendChild(table);
}
And here the the result I get:
My question is why do I get "McDowell" not under the family name column.Why it is shifted?What I am missing?

Try to create a new th for the second time, don't use the already used one
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement("thead");
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
//********* Look here *****************
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th'); //*** Create a new th here. Dont use the old one
//********* Look here *****************
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'))
tr.cells[1].appendChild(document.createTextNode('McDowell'))
table.appendChild(tr);
}
tablearea.appendChild(table);
}
DEMO

SOLUTION
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th');
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'));
tr.cells[1].appendChild(document.createTextNode('McDowell'));
table.appendChild(tr);
}
tablearea.appendChild(table);
}
CreatTable();

you miss creating new th
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th'); // this line missed
th.appendChild(familyNameTxt);

Create dynamic table row and remove on click delete button row. for this you can use jQuery two method
.append() this method used for append html table row, on button click of .add_row_record its get value from text box and append data on table row.
.remove () this method is used for remove dynamic content data, in this example we are used for delete append record. .delete_row_record button remove the record on the basis of selected checkbox.
<script type="text/javascript">
$(document).ready(function(){
//add row
$(".add_row_record").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var mobile = $("#mobile_number").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td><td>" + mobile + "</td></tr>";
$("table tbody").append(markup);
});
// select record for delete
$(".delete_row_record").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
Demo

Related

JS and DOM, trying to create table

I tried to create table but I can't create td in every tr, td is creating only in first td what is in table, how I can solve the problem?
// Creating div
var main = document.createElement("div")
main.innerHTML = ""
document.body.appendChild(main)
main.setAttribute("id", "main")
//Creating Icons
var puzzleico = document.createElement("div")
puzzleico.innerHTML = ""
document.getElementById("main").appendChild(puzzleico)
puzzleico.setAttribute("id", "puzzleico")
var puzzleico = document.getElementById("puzzleico").onclick = function() {createtable()};
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr").appendChild(td)
}
}
Element id's within a document need to be unique. The issue here is that your document.getElementById("tr") will always return the first element it finds with that id and so, all of your <td> elements will be appended to the first <tr>.
In order to fix it you can remove the tr.setAttribute("id", "tr") line and use the already existing tr variable to append the td child to.
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test"
tr.appendChild(td)
}
}
createtable();
The above code will work, but using the already declared variables instead of finding them again can also be applied to the table case. Also, table.innerHTML = "" doesn't add any value because the innerHTML is already empty when you create a new element.
function createtable() {
//Creating Table
var table = document.createElement("table");
document.body.appendChild(table);
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test";
tr.appendChild(td);
}
}
You can use this to create the table:
function createTable(){
//Creating And Appending Child
let table = document.createElement('table');
document.body.appendChild(table);
for(let i = 0; i < 50; i++){
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = i;
tr.appendChild(td);
table.appendChild(tr);
}
}
Here is the link to my codepen:
https://codepen.io/prabodhpanda/pen/gOPLqYe?editors=1010
id attribute of each element in DOM should be unique. You set same id for each tr element you create. document.getElementById element always returns the first element match by the id. This is the reason of the issue. Your last code snippet should be:
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr" + i) // Check this
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr" + i).appendChild(td) // Check this
}
}
tr.appendChild(td) should also work if you don't need ID attribute.
I edited your answer and got what I want.
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
for (var v = 0; v < 50; v++) {
var td = document.createElement("td")
td.innerHTML = ""
tr.appendChild(td)
}
}
}

Can't display the checkbox and button in every rows of td

I can't display the checkbox and button in every rows of td. Currently it appending in last rows td only. and how to append the checkbox and buttons in all rows in td.. Can anyone help me to do this?
for (var i = 0; i < obj.length; i++) {
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(checkbox);
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = i;
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
var cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(btnEdit);
cell.appendChild(btnSave);
}
JsFiddle
Basically what is happening is you are moving the input/buttons every time you append them to the cell because it is the same element.
To fix this you must create the checkbox and buttons in your for loop.
for (var i = 0; i < obj.length; i++) {
var btnSave = document.createElement('button');
btnSave.setAttribute ("id","saveBtn");
btnSave.innerHTML = "Save";
var btnEdit = document.createElement('input');
btnEdit.type = "button";
btnEdit.value = "Edit";
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id= "checkBox";
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(checkbox);
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = i;
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
var cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(btnEdit);
cell.appendChild(btnSave);
}
Just as a side note, it is good practice that 'id' attributes be unique.
Hope this helps.

Adding <th> to the table in js

I'm trying to add <th> tag to the table, but I am not able to add. I want to add Id, Name and Prof as a table header.
var obj=[{id:"01",name:"Bob",prof:"Soft Engg"},{id:"02",name:"George",prof:"Admin"},{id:"03",name:"Paul",prof:"Front End"}];
var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);
for(i=0;i<obj.length;i++) {
var row = document.createElement("tr")
table.appendChild(row);
var head = document.createElement("th");
row.appendChild(head);
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
You can do something like this
var obj = [{
id: "01",
name: "Bob",
prof: "Soft Engg"
}, {
id: "02",
name: "George",
prof: "Admin"
}, {
id: "03",
name: "Paul",
prof: "Front End"
}];
var table = document.createElement("table");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
// check array length
if (obj.length) {
// create row for table head
var row = document.createElement("tr")
// append it to table
table.appendChild(row);
// get kesys from first object and iterate
Object.keys(obj[0]).forEach(function(v) {
// create th
var cell = document.createElement("th");
// append to tr
row.appendChild(cell);
// update th content as key value
cell.innerHTML = v;
});
}
for (var i = 0; i < obj.length; i++) {
var row = document.createElement("tr")
table.appendChild(row);
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
I couldn't stop thinking about this post and use it as JS practice, here I go:
var obj=[
{id:"01",name:"Bob",prof:"Soft Engg"},
{id:"02",name:"George",prof:"Admin"},
{id:"03",name:"Paul",prof:"Front End"}
];
var headers=['id','name','prof'];
var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);
var tableHeader = document.createElement("thead");
table.appendChild(tableHeader);
tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for(i=0;i<headers.length;i++){
var tableHeader = document.createElement("th");
tableHeaderRow.appendChild(tableHeader);
tableHeader.innerHTML = headers[i]
}
var tableBody = document.createElement("tbody");
table.appendChild(tableBody);
for(i=0;i<headers.length;i++){
var tbodyrows=document.createElement("tr");
for (key in obj[i]) {
tableBody.appendChild(tbodyrows);
var cell = document.createElement("td");
tbodyrows.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}

Creating dynamically large table using JavaScript

I'm trying to create dynamically a table using JavaScript.
Here is the code I'm using (or here http://liveweave.com/mqG5iT):
function Process(){
CreatTable(['First Name', 'Last Name', 'Email']);
}
function CreatTable(data) {
var checkbox;
var table;
var thead;
var tr;
var th;
var tbody;
tablearea = document.getElementById('ShowDataID');
table = document.createElement('table');
table.id = "ContactsTable";
thead = document.createElement('thead');
tr = document.createElement('tr');
tbody = document.createElement('tbody');
//create columns input checkbox column
checkbox = CreateHTMLElement("chkBoxAllEmails", "chkBoxAllEmails", "SelectAllEmails()", "checkbox", "false");
th = document.createElement('th');
th.appendChild(checkbox);
tr.appendChild(th);
thead.appendChild(tr);
//create columns FirstName,LastName,Emails
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
//create rows and addind to table
for (var i = 0; i < 2000; i++) {
tr = document.createElement('tr');
checkbox = CreateHTMLElement("11", "11", "11", "checkbox", "11");
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(checkbox); tr.cells[1].appendChild(document.createTextNode('John'+i.toString()));
tr.cells[2].appendChild(document.createTextNode('McDowell'));
tr.cells[3].appendChild(document.createTextNode('ddd#gmail.com'));
tbody.appendChild(tr);
table.appendChild(tbody);
}
document.getElementById("TablePagingArea").appendChild(table);
//return table;
}
function CreateHTMLElement(id, name, onclick, type, value) {
var HTMLElement = document.createElement('input');
HTMLElement.id = id;
HTMLElement.name = name;
HTMLElement.onclick = onclick;
HTMLElement.type = type;
HTMLElement.value = value;
return HTMLElement;
}
With a small set of data 1000-3000 rows it works relatively well but, some of the data set contains upwards of 5000 rows which causes Firefox to crash and close or become unresponsive.
My question is: is there a better way to accomplish what I am trying to do?
Most efficient way to create a bunch of elements is to create a string and create element from this string.
Most efficient way to create a string of element is to join from array
So you should refactor your code to
Create an array of elements like a[i] = "<tr><intput type='checkbox'></tr>";
Join an array to get one string var s = a.join();
Create DOM elements like var div = document.createElement('div'); div.innerHTML = s;

How to create checkbox column in the table?

I am dynamically creating a table using JavaScript code below:
function CreatTable(data) {
var tablearea;
var table;
var thead;
var tr;
var th;
tablearea = document.getElementById('ShowDataID');
table = document.createElement('table');
thead = document.createElement('thead');
tr = document.createElement('tr');
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'));
tr.cells[1].appendChild(document.createTextNode('McDowell'));
tr.cells[2].appendChild(document.createTextNode('ddd#gmail.com'));
table.appendChild(tr);
}
tablearea.appendChild(table);
}
</script>
When I create table I also need to create checkbox column in the table above.
Any idea how I can implement it using JavaScript?
Or related link?
I'm not sure if this is what you're asking:
var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
and then you'd append checkbox to each row in order to form a new column.
See this fiddle: http://jsfiddle.net/qeeu18g1/3/
I added comments where I added things.
(is this a duplicate of this question?)
Use the following JS code:
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("name", "city");
x.setAttribute("value", "London");
x.setAttribute("id", 1);
And place it whereever you want to add it.
See more at HTML DOM Input Checkbox Object

Categories

Resources