Dynamically generated table - using an array to fill in TD values - javascript

I need your help,
For some reason, I can't get the data captured in my array to populate into the TD cells of my dynamically generated table:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "Request Type"
heading[1] = "Group A"
heading[2] = "Groub B"
heading[3] = "Group C"
heading[4] = "Total"
var stock = new Array()
stock[0] = new Array("Cars", "88.625", "85.50", "85.81", "987")
stock[1] = new Array("Veggies", "88.625", "85.50", "85.81", "988")
stock[2] = new Array("Colors", "88.625", "85.50", "85.81", "989")
stock[3] = new Array("Numbers", "88.625", "85.50", "85.81", "990")
stock[4] = new Array("Requests", "88.625", "85.50", "85.81", "991")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < stock.length; i++) {
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td)
}
}
myTableDiv.appendChild(table)
}
</script>
</head>
<div id="metric_results">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
</div>
</body>
</html>

Change:
var tr = document.createElement('TR'); // this should be inside the first loop
tableBody.appendChild(tr); // this should be just before the first loop is over
for (i=0; i<stock.length; i++) {
for (j=0; j<stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td) // this should be tr.appendChild(td)
}
}
to this:
for (i = 0; i < stock.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
Fiddle

Related

Javascript : Creating a dynamic table with column title on the first row and row title in the first column

I am trying to create a table with title to be displayed on the first and second row and first column. The first row will have the same name which is working fine. But with my below script the row title (starting from 3rd row) displays in the last column than the first.
Please advise where am I going wrong with this.
var body = document.getElementsByTagName("body")[0];
var yardName = "B1";
var colsInYard = 5;
var rowsInYard = 5;
var tbl = document.createElement("table");
tbl.setAttribute("id", "our_table");
var tblHead = document.createElement("thead");
for (var r = 0; r < 1; r++) {
// creates a table row
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(yardName);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
for (var r = 0; r < 1; r++) {
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(c);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
tbl.appendChild(tblHead);
var tblBody = document.createElement("tbody");
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "0");
tbl.setAttribute("cellpadding", "0");
tbl.setAttribute("cellspacing", "0");
My fiddle https://jsfiddle.net/udopgxLv/1/
I believe you just need to add an IF statement to the code in the tbody section to get the data to post into the first column. I modified your jfiddle with the code below (just 2 lines added) and the values are inserted properly.
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c==1){ // <--- this was added
cell.appendChild(cellText);
} // <--- this was also added
row.appendChild(cell);
}
tblBody.appendChild(row);
}
You missed if statement in create tbody
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c=== 0)
cell.appendChild(cellText);
row.appendChild(cell);
}
https://jsfiddle.net/udopgxLv/3/

Create table column-headers dynamically

Right now I cannot figure out how to add headers for all the columns in this code where a html-table are created dynamically
function createTableAndInsert(sqlArray) {
//create table dynamically - only one row by the moment
var table = document.createElement('table');
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
You can pass the header list separately to your function and add following code
function createTableAndInsert(sqlArray,headerList) {
var table = document.createElement('table');
var tr = document.createElement('tr'); // Header row
for (var j = 0; j < 8; j++) {
var th = document.createElement('th'); //column
var text = document.createTextNode(headerList[j]); //cell
th.appendChild(text);
tr.appendChild(th);
}
table.appendChild(tr);
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
Your structure is:
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
thead should be appended before each row.
<thead></thead>
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
Solution:
var thead = document.createElement('thead');
thead.innerHTML = 'Header';
Before table.appendChild(tr);, add this line table.appendChild(thead);
THEAD needs one or more TR elements:
var table = document.createElement('table'); // 'table' may be a reserved word
var tblHead = document.createElement('thead');
var rowHead = document.createElement('tr');
table.appendChild(tblHead);
tblHead.appendChild(rowHead)
for(j=0; j<8; j++) {
var celHead = document.createElement('th');
//the array txtHeaders[] should be passed to your function if you have the values in advance
// otherwise, you can access the header cells later by:
// table.getElementsbyTagName('th')[].innerHTML
celHead.innerHTML = txtHeaders[j]
rowHead.appendChild(celHead)
}
// now do your row & table loops

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

Datatable not working properly

So I am generating a table with results which are returned from a JSON that is searched through and I would like to table to have pagionation, search, sorting options so I decided to use Data Tables. The table is being generated and populated with the correct results but the sorting options, the search and the pagination options do not appear at all. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Конкуренција</title>
</head>
<body>
<div id="cars" class="cars-container"></div>
<label for="amount">Цена:</label>
<input type="text" class="price-range-slider" id="amount" onclick="myFunction()" readonly style="border:0; color:#f6932f; font-weight:bold">
<div id="slider-range" style="width:300px"></div>
<br>
<p>
<label for="sili">Коњски сили:</label>
<input type="text" id="sili" onclick="myFunction()" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="rejndz" style="width:300px" ></div>
<div>
<h4><label>Бренд</label></h4>
<select id="brand" multiple="multiple" onclick="myFunction()" data- style="btn-primary">
</select>
</div>
<br>
<div>
<h4><label>Тип на мотор</label></h4>
<select id="engineCap" multiple="multiple" onclick="myFunction()" >
</select>
<button onclick="myFunction(); dataTable(); ">Барај</button>
</table>
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}
These are the errors I get in console:
Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at jQuery.fn.init.each (jquery.js:157)
at jQuery.fn.init.p [as dataTable] (jquery.dataTables.min.js:80)
at dataTable (index.html:268)
at HTMLButtonElement.onclick (index.html:75)
Assigning value to finalKola in the following code. This code takes values from two range slider and two buttons and searches through a JSON.
for(var u=0;u<koli.length;u++)
{
if((koli[u].sili > minSili) && (koli[u].sili < maxSili) && (parseInt(koli[u].amount.replace(',','')) > minCena) && (parseInt(koli[u].amount.replace(',','')) < maxCena))
{
if( (kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1))
{
finalKola.push(koli[u]);
}
else if(kapacitet.length == 0 && selected.length == 0)
{
finalKola.push(koli[u]);
}
else if((kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length == 0))
{
finalKola.push(koli[u]);
}
else if((selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1) &&
(kapacitet.length == 0))
{
finalKola.push(koli[u]);
}
}
}
I think DataTable is not applying on your table as you are applying datatable on $(document).ready and creating table in your function.
You can apply datatable after you have created the table.
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$('#results').dataTable().fnDestroy();
$('#results').dataTable();
}
Your script is adding tbody before the thead, changed that to append Thead tr first and then tbody.
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
myTableDiv.appendChild(tableBody);
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}

Creating a table with a loop

I'm quite new to Javascript and I'm trying to populate a table through a loop. The code works fine as long as I only try to populate the table, but when I try to add an IF condition in order to separate headers and data, it does not work any more. I would be curious to understand why it does not work and how can I solve the issue.
Below current broken code:
for(i = 0;i < values.length; i ++){
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
if (i=0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
} else {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
}
Here the code that works without headers:
for(i = 0;i < values.length; i ++){
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
table.appendChild(tr);
}
you should put double equal i==0 not i=0
if (i==0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
EDIT
in your second loup you should close the if statement and loop :
for (i = 0; i < values.length; i++) {
var table = document.getElementById("myTable");
tr = document.createElement('tr');
for (j = 0; j < values[i].length; j++) {
if (i == 0) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
} else {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = values[i][j];
}
}
}

Categories