Populate table from array using JQuery - javascript

I have an array of 16 elements that I want to fill a table. I want it to have 2 rows with 8 cells in each row which is filled with the array. My problem is that when the table is populated, the table populates all elements into one row. I have not had much experience with JQuery and I want to try to get this to work. Any help is appreciated! Here is my code:
//**********Javascript & JQuery**********
var array = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var count = 0;
var totalCells = 8;
function writeTable() {
var $table = $('#summaryOfResults');
//Array always includes enough elements to fill an entire row, which is 8 cells. Outer loop determines how many rows to make.
//Inner loop determines the elements to print in the cells for that row.
for (var i = 0; i < array.length / 8; i++) {
$table.find('#body').append('<tr>');
for (var j = 0; j < totalCells; j++) {
$table.append('<td>' + array[count] + '</td>');
count++;
}
$table.append('</tr>');
}
}
//**********HTML**********
<html>
<head>
</head>
<body>
<div id="resultsTable">
<table id='summaryOfResults' border='1'>
<tbody id="body">
<tr>
<th>#</th>
<th>n<sub>i</sub></th>
<th>n<sub>f</sub></th>
<th>E<sub>i</sub> (J)</th>
<th>E<sub>f</sub> (J)</th>
<th>ΔE (J)</th>
<th>ΔE (kJ/mol)</th>
<th>λ (nm)</th>
</tr>
</tbody>
</table>
</div>
<div id="tableButtons">
<button id='copyButton' onclick=''>Copy Table</button>
<button id='clear' onclick='clearTable();'>Clear Table</button>
<button id='write' onclick='writeTable();'>Write Table</button>
</div>
</body>
</html>

First, you have to reset count on every click.
Next, you have to specify where exactly the <td> elements have to be appended to. As for now, you're appending them directly to the <table> :
// your declaration of the table element:
var $table = $('#summaryOfResults');
// ...
// then in nested loop, you're appending the cells directly to the table:
$table.append('<td>' + array[count] + '</td>');
The last thing - .append('</tr>') is not a proper way to create an element object, it should be '<tr/>' , or '<tr></tr>'.
This should be what you're looking for:
function writeTable() {
// cache <tbody> element:
var tbody = $('#body');
for (var i = 0; i < array.length / 8; i++) {
// create an <tr> element, append it to the <tbody> and cache it as a variable:
var tr = $('<tr/>').appendTo(tbody);
for (var j = 0; j < totalCells; j++) {
// append <td> elements to previously created <tr> element:
tr.append('<td>' + array[count] + '</td>');
count++;
}
}
// reset the count:
count = 0;
}
JSFiddle
Alternatively, make a HTML string and append it to the table outside of the loop:
function writeTable() {
// declare html variable (a string holder):
var html = '';
for (var i = 0; i < array.length / 8; i++) {
// add opening <tr> tag to the string:
html += '<tr>';
for (var j = 0; j < totalCells; j++) {
// add <td> elements to the string:
html += '<td>' + array[count] + '</td>';
count++;
}
// add closing </tr> tag to the string:
html += '</tr>';
}
//append created html to the table body:
$('#body').append(html);
// reset the count:
count = 0;
}
JSFiddle

Related

Create table of specified column and rows in Jquery

I am new to jQuery, I want to create table with specific number of rows and columns in jQuery.
Here is what I tried this creates table with specific number of rows but it doesn't create table of specific number of columns
function constructTable () {
let table = $('<table>').first().prepend('<caption><b> Borrow </b></caption>');
let row;
let cell1;
let cell2;
table.attr({"id":"burrow"});
for(i=0; i < 3; i++) {
row = $('<tr>');
table.append(row);
}
for ( i = 0 ; i < 4; i++ ) {
cell1 = $('<td>').text('cell ' + i);
row.append(cell1);
}
$("#borrowLicensediv").append(table);
document.getElementById('borrowLicensediv').style.display = '';
}
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="constructTable ()" style="background: white;">
<div id="borrowLicensediv" style="display: none; margin-top:10px; margin-bottom:25px; margin-left:20px; margin-right:37px;"></div>
</body>
</html>
Before you append rows to the table these must first have cells otherwise you're going to have empty rows in your table with no columns. Leaving jQuery aside for a moment, the general problem is:
Build a row
Append it to the table
Repeat 1 and 2 for all rows to add
Step (1) implies that you first create the cells you want in the row and add them to the row. This means you're going to have nested loops (whereas in your example they're inline).
You need something more like
for(i=0; i < 3; i++) {
var row = "<tr>";
for ( j = 0 ; j < 4; j++ ) {
var value = "cell " + i + "," + j;
var td = "<td>" + value + "</td>";
row += td;
}
row += "</tr>";
table.append(row);
}
You are adding the TDs to the last Row because your cell loop is outside of the Row loop. We need to move the loop inside and fix the iterator variable, like this:
for(var r=0; r < 3; r++) {
row = $('<tr>');
for ( var c = 0 ; c < 4; c++ ) {
cell = $('<td>').text('cell ' + r+c);
row.append(cell);
}
table.append(row);
}

jQuery, adding multiple table rows is not working correctly

The idea is to build a function that takes an input and uses that to build a grid. I'm trying to establish the grid functionality first, and I'm having a peculiar error. I searched for a few hours, but the answers all tell me that a simple "append" should be working.
The specific error that I am getting:
When I load up the webpage, it is only adding one table row to the tbody, and only one table data to that table row. The idea is instead to create a grid of 16 x 16, with 16 rows and 16 data. Console logs show that the loops are all working correctly.
The html is just a basic file that imports the javascript correctly (All tested) with a simple:
div class="container" /div
Code:
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
//blank rows to insert
var blankResults = $("<table>");
var result = blankResults;
var row = $("<tr/>");
var data = $("<td/>");
function makeTable(num)
{
result = blankResults;
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
//add data num times
for (var j = 0; j < num; j++)
{
console.log(j);
row.append(data);
}
//append row
console.log(i);
result.append(row);
}
}
//starting area
makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
Try this code.
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
function makeTable(num)
{
var output = '<table>';
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
output+= '<tr>'
for (var j = 0; j < num; j++)
{
output += '<td></td>';
}
output += '</tr>';
}
output += '</table>';
return output;
}
//starting area
var result = makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
You are appending to the same variables all the time...row and 'data`. you should not do that.
As you can see from the code below, you need to create the var row = $("<tr>"); on each loop, to reference it when you append the <td> (table cell) to that newly created row.
Modifed to use only one loop:
$(document).ready(function(){
function makeTable(num) {
var table = $("<table>"), row;
for (var i = 0; i < num; i++){
row = $("<tr>");
table.append(row);
row.append(Array(num + 1).join("<td></td>"));
}
return table;
}
$(".container").html(makeTable(16));
});
DEMO PLAYGROUND
Of course, this is not a good way generating a table. running jQuery function on each loop is slow and bad practice. You should generate a big string which will represent your DOM structure and then append that string where needed and jQuery will make a DOM node out of it.
I made up my own html for this but it should be as simple as using two nested for loops grabbing values the size input. Here's what I came up with:
$("#tableMaker").click(function () {
$('.container').html("");
$('.container').append("<table></table>");
for (var i = 0; i < $('#size').val(); i++) {
$('table').append("<tr></tr>");
for (var j = 0; j < $('#size').val(); j++) {
$('tr:last').append("<td>Column " + (j+1) + ", Row " + (i+1) + "</td>");
}
}
})
td {
border: black solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="size" placeholder="Size" />
<button id="tableMaker" type="button">Generate Table</button>
<br />
<div class="container">
<div />

Show total no. rows for in HTML <span>

I need your help in displaying the total number of rows for the available tables in the appropriate span. There are 3 tables and I want the below code to show the total no. of rows in the first table in span1 & the total no. of rows for the second table in span2.
The JavaScript is:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
var span = Array();
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
alert(span[i]);
span[i].innerHTML = rows;
}
}
However, span[i] is not picking up the value and print it in the HTML span.
The HTML code is:
<body>
<span id="span1"></span>
<span id="span2"></span>
<span id="span3"></span>
</body>
I am looking forward your assistant and help.
Use this function instead:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
document.getElementById("span" + (i + 1)).innerHTML = rows;
}
}
You are never referring to the span, so that is why I used
document.getElementById("span" + (i + 1)).innerHTML = rows;

Trying to take the number from the first column of each row, and insert it as the id of the <tr> element

Here's my code. I am trying to take the value of the innerHTML for each row of a column in my table, and then add this to a <tr> element as <tr id="1"> <tr id="47">, etc
window.onload = function inventorytable() {
var tableRows = document.getElementById("inventorytable").rows;
var idxarray = "";
for(var i = 1, l = tableRows.length; i < l; i++) {
var tds = tableRows[i].cells;
tds[7].innerHTML += " Ghz"
tds[8].innerHTML += " GB"
tds[10].innerHTML += " Mhz"
idxarray = idxarray += tds[0].innerHTML //THIS IS WHERE I AM NOT SURE WHAT TO DO
}}
How do I take the information contained in tds[0].innerHTML for each row, and put it as that row's id?
I'm a little confused. Are you trying to take the inner-html of column 0 of each row and make that the id (prepended with row-) of the parent tr? If so would this do the trick?...
window.onload = function inventorytable() {
var tableRows = document.getElementById("inventorytable").rows;
for(var i = 1, l = tableRows.length; i < l; i++) {
var tds = tableRows[i].cells;
tds[7].innerHTML += " Ghz"
tds[8].innerHTML += " GB"
tds[10].innerHTML += " Mhz"
tableRows[i].id = 'row-' + tds[0];
}
}

Getting value from table cell in JavaScript...not jQuery

I can't believe how long this has taken me but I can't seem to figure out how to extract a cell value from an HTML table as I iterate through the table with JavaScript. I am using the following to iterate:
var refTab=document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
What is the correct call I should be putting in to the alert() call to display the contents of each cell of my HTML table? This should be in JS...can't use jQuery.
function GetCellValues() {
var table = document.getElementById('mytable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
}
I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...
if(document.getElementsByTagName){
var table = document.getElementById('table className');
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
alert('col html>>'+col.innerHTML); //Will give you the html content of the td
alert('col>>'+col.innerText); //Will give you the td value
}
}
}
}
If I understand your question correctly, you are looking for innerHTML:
alert(col.firstChild.innerHTML);
confer below code
<html>
<script>
function addRow(){
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e =table.rows.length-1;
var l =table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c =0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn(){
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " " ;
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0);//var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});
In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table id='ddReferences'>
<tr>
<td>dfsdf</td>
<td>sdfs</td>
<td>frtyr</td>
<td>hjhj</td>
</tr>
</table>
<script>
var refTab = document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
</script>
</body>
</html>
the above guy was close but here is what you want:
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].firstChild.value);
}
}
}catch(e) {
alert(e);
}
If you are looking for the contents of the TD (cell), then it would simply be: col.innerHTML
I.e: alert(col.innerHTML);
You'll then need to parse that for any values you're looking for.
Have you tried innerHTML?
I'd be inclined to use getElementsByTagName() to find the <tr> elements, and then on each to call it again to find the <td> elements. To get the contents, you can either use innerHTML or the appropriate (browser-specific) variation on innerText.
A few problems:
The loop conditional in your for statements is an assignment, not a loop check, so it might infinite loop
You should use the item() function on those rows/cells collections, not sure if array index works on those (not actually JS arrays)
You should declare the row/col objects to ensure their scope is correct.
Here is an updated example:
var refTab=document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; i<refTab.rows.length; i++ ) {
var row = refTab.rows.item(i);
for ( var j = 0; j<row.cells.length; j++ ) {
var col = row.cells.item(j);
alert(col.firstChild.innerText);
}
}
Replace innerText with innerHTML if you want HTML, not the text contents.
Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:
alert(col.firstChild.value);
Try this out:
alert(col.firstChild.data)
Check this out for the difference between nodeValue and data:
When working with text nodes should I use the "data", "nodeValue", "textContent" or "wholeText" field?
<script>
$('#tinh').click(function () {
var sumVal = 0;
var table = document.getElementById("table1");
for (var i = 1; i < (table.rows.length-1); i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("valueTotal").innerHTML = sumVal;
});
</script>

Categories

Resources