Using JavaScript to create a table - javascript

I'm supposed to create a table like this from scratch using JavaScript and I have no idea how.
Am I supposed to use array for this?
I'm still new to JavaScript and this is my first week of learning it. Thanks for the help!
BMI Health category
Below 18.5 Under weight
Between 18.5 and 23 Normal weight
Between 23 and 27.5 Over weight
Above 27.5 Obese

Creating table in Pure JS:
var table_header = ['BMI', 'Health category'];
var table_rows = [
['Below 18.5', 'Under weight'],['Between 18.5 and 23', 'Normal weight'],
['Between 23 and 27.5', 'Over weight'],['Above 27.5', 'Obese']
];
var dom_body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
var tbody = document.createElement('tbody');
//use for loop to add row and cells into the table body
var tr = document.createElement('tr');
table_header.forEach(function(value,index){
var td = document.createElement('td'); //table cell
td.innerHTML= value; //set cell value
tr.appendChild(td); //add it into row
})
tbody.appendChild(tr); //add table header
//insert table rows
table_rows.forEach(function(row,index){
var tr = document.createElement('tr');
//append cells for this current row
row.forEach(function(value,index){
var td = document.createElement('td'); //table cell
td.innerHTML= value; //set cell value
tr.appendChild(td); //add it into row
})
tbody.appendChild(tr); //add row
})
//add the table in the dom
table.appendChild(tbody);
dom_body.appendChild(table);

Related

Add links to all cells in column of html table

I would like to loop through the cells in the second column of an html table, adding a link to the text in each cell. I have a generic base URL, with a hash that should be defined by an integer in the corresponding cell in the first column of the table.
For example, the text in first cell of the second column should link to:
http://test.example.com/foo.html#1
Where the #1 is defined by the integer in the first cell of the first column (1). Then repeat for each row, where the integer in each cell of the first column should be used for the hash.
Pure js or jquery would work. I have found this snippet of jquery, which seems like a good start for iterating through each cell in the second column:
$('#table1 td:nth-child(2)').each(function(elem) {
//do something with elem
});
Is this jquery method appropriate, and if so, how can I apply the links as described?
As a possible alternative, could I modify the function I use to create the table?:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
Since you are the one creating the table at the first place it is best to modify the code and render it correctly (as oppose to updating it later on client-side).
Based on your comments and clarification here is the updated code, storing the integer value of first column of each row to use it as url on second column:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
var theUrl = 'http://test.example.com/foo.html#'; //replace with real URL
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
var i = 1;
var numValue = '';
var content = '';
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
numValue = (i==1) ? cellData : numValue ;
if(i==2){
content = document.createElement('a');
content.setAttribute('href', theUrl + numValue);
content.innerText = cellData ;
}
else{
content = document.createTextNode(cellData);
}
cell.appendChild(content);
row.appendChild(cell);
i++;
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
You may change the following code:
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
to
for (var i=0; i<rowData.length;i++)
{
var cell = document.createElement('td');
if (i==1)
{
var link=document.createElement("a");
link.href="http://test.example.com/foo.html#"+(i+1);
link.text=rowData[i];
cell.appendChild(link);
}
else
cell.textContent=rowData[i];
row.appendChild(cell);
}

How to assign variable ids to tables rows and columns

How can I assign ids to the rows, columns if I want to use this method for creating tables. Knowing that the ids are variables, eg. array length.
function addRow(tableID, text) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table
var newRow = tableRef.insertRow();
// Insert a cell in the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode(text);
newCell.appendChild(newText);
}
// Call addRow(text) with the ID of a table
addRow('TableA', 'Brand new row');
addRow('TableA', 'Another new row');
Let us say you want to add k rows. Simple, create the rows in a loop of k iteration.
var tableRef = document.getElementById(tableID);
//to add k rows
for (x=0; x<k; x++)
{
// Insert a row in the table
var newRow = tableRef.insertRow(x);
newRow.setAttribute("id","row"+x);
// Insert a cell in the row
var newCell = newRow.insertCell(0);
// Insert another cell in the row
var newCell2 = newRow.insertCell(1);
//insert HTML text in the cells
newCell.innerHTML="text1";
newCell2.innerHTML="text2";
} //end for
}//end function

For 2 dynamically generated TD

Right now the following code generates two much white spaces between the two TDs.
How to set the first TD left aligned and
the second TD left aligned to the first TD?
// nTR being the newly TR
nTR.setAttribute('style','td {padding: 10px}') has no effect. How to go about it?
// creating row and creating all cells
// creates a table row
var newrow = document.createElement("tr");
newrow.setAttribute('style','td {padding: 10px}');
// cell 1
var cell = document.createElement("td");
cell.colSpan = "2";
// cell.setAttribute('style','padding: 10px');
var cellText = document.createElement('input');
cellText.type = 'text';
cellText.id = 'fLabel';
cellText.name = 'fLabel';
cellText.size = "20";
cell.appendChild(cellText);
newrow.appendChild(cell);
// cell 2
var cell = document.createElement("td");
cell.colSpan = "3";
var cellText = document.createElement('input');
cellText.type = 'text';
cellText.id = 'fValue';
cellText.name = 'fValue';
cellText.size = "80";
cell.appendChild(cellText);
newrow.appendChild(cell);
// code to append the new TR to table
// ...
Thanks.

Bootstrap Table not appearing correctly

I am using JavaScript to loop through some data and build a number of tables and am using Bootstrap with the class table table-hover. This works absolutely fine on all tables except the very last table to be produced. The bottom table is always sqashed and the hover over doesn't work. The columns resize to the correct size but that's about it.
I can't work it out, both tables have the class declared:
No matter how many tables are made it always happens on the very last table. I should point out that I've tried everything I can think of including adding a dummy table within the loop and the last interation but then that makes two squashed tables then.
Update: http://jsfiddle.net/si828/1ksyces5/8/
Code:
$('#tableContainer').empty();
var div = document.getElementById('tableContainer');
for (var i = 0; i < data.length; i++)
{
div.innerHTML = div.innerHTML;
var para = document.createElement("p");
var logo = document.createElement("a");
logo.setAttribute('class', 'glyphicon glyphicon-user');
para.appendChild(logo);
var node = document.createTextNode(" " + data[i].userName + " (" + data[i].userID + ") " );
para.appendChild(node);
var aTag = document.createElement("a");
aTag.setAttribute('data-id-proxy' , data[i].userID);
aTag.setAttribute('class' , 'open-AddUserModal');
aTag.setAttribute('href' ,'#addUserModal');
var span = document.createElement("span");
span.setAttribute('class', 'glyphicon glyphicon-plus');
aTag.appendChild(span);
para.appendChild(node);
para.appendChild(aTag);
para.setAttribute('class', 'text-primary');
div.appendChild(para);
var table = document.createElement('table'), tr, td, row, cell;
table.setAttribute('class', 'table table-hover');
table.setAttribute('id', 'table' + data[i].userID);
table.setAttribute('border', '1');
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "SRM";
var cell = row.insertCell(1);
cell.setAttribute('style' , 'width: 13%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User";
var cell = row.insertCell(2);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User Name";
for (row = 0; row < data[i].targetUsers.length; row++)
{
tr = document.createElement('tr');
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].srm;
table.appendChild(tr);
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUser;
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUserName;
}
document.getElementById('tableContainer').appendChild(table);
}
Based on your JSFiddle, your div.innerHTML = div.innerHTML; on line 10 should be the last statement of your outer for loop (on line 76). Otherwise your table doesn't get a <tbody>, causing bootstrap to malfunction.
Here is the fixed one: http://jsfiddle.net/wsLzk5wq/
If it is only the last table you could add custom css for the last table element by using a child selector.
E.g
HTML:
<div class="parent-container">
<table>
.......
</table>
</div>
CSS:
.parent-container table:last-child {
padding: 10px !important;
.......
}

How to delete the table row on button click

var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onclick = function(){ };
var table = document.getElementById("myTableData");
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD');
td.width='175';
td.appendChild(el);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(objLabel);
td.appendChild(objLabel2);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(el_s);
td.appendChild(el_sm);
td.appendChild(el_sy);
tr.appendChild(td);
**var td = document.createElement('TD');
td.width='20';
td.appendChild(del);
tr.appendChild(td);**
myTableData.appendChild(table);
In the above code I have created a table dynamically and added NAME field GENDER field and DATE OF BIRTH field and DELETE BUTTON.
The code works like this: first the user has to enter details in NAME GENDER AND DOB, if the DELETE button is clicked then the columns containing fields are deleted from the table.
I have to insert the code for deletion here:
del.onclick = function(){ };
Try this:
del.onclick = function(){
var tr = document.createElement('TR');
tr.parentElement.removeChild(tr);
};

Categories