How to put the elements of array of arrays in table cells? - javascript

<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix()
{
var e=prompt("Cols?",0);
var f=prompt("Rows?",0);
var matrix = new Array();
for (var i=0;i<e;i++)
{
matrix[i] = new Array();
for (var j=0;j<f;j++)
{
matrix[i][j]=Math.floor((Math.random()*1000)+1);
}
}
for (var i=0; i<=e-1; i++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<tr>";
for (var j=0; j<=f-1; j++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<td>"+matrix[i][j]+"</td>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</tr>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</table>";
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret">
</body>
</html>
This script makes a user defined array of arrays, and filling it up with random numbers. My problem is:
I can't make the script to put the values in dividual cells.

Your second loop can be as follows:
for (var i = 0; i < e; i++) {
var row = document.createElement("tr");
for (var j = 0; j < f; j++) {
var cell = document.createElement("td");
cell.innerHTML = matrix[i][j];
row.appendChild(cell);
}
document.getElementById("keret").appendChild(row);
}
This appends a tr element for each row and a td element for each column within the row. Then it appends the row to your table. Your HTML would be slightly modified as well:
<table border="1" id="keret"></table>
(Rows & Columns prompts need to be switched but I didn't want to mess up your variable names).
Fiddle: http://jsfiddle.net/verashn/7Rwnc/

<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix() {
var e = prompt("Cols?",0),
f = prompt("Rows?",0),
allRows = [],
row = [];
for (var i = 0; i < e; i += 1) {
row = ['<tr>', '</tr>']; // this serves as your initial template
for (var j = 0; j < f; j += 1) {
// now create the columns
row.splice(-1, 0, '<td>' + Math.floor((Math.random()*1000)+1) + '</td>')
}
allRows.push(row.join(''));
}
document.getElementById("keret").innerHTML = allRows.join('');
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret"></table>
</body>
</html>

Related

How to insert an HTML table in Javascript?

I need to write a JS function called addMultiTable(rows, cols) that will create a multiplication table with 4 rows and 8 columns, and append it after the header:<h1>Multiplication Table</h1>.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table</title>
</head>
<body>
<h1>Multiplication Table</h1>
</body>
</html>
This should work for you, remember there are a few ways to solve this problem
function addMultiTable(rows, cols) {
var table = document.createElement("table"),
elem = document.getElementsByTagName("h1")[0],
i = 1,
j = 1,
val = 0;
for( i; i <= rows; i++ ) {
var row = document.createElement("tr");
for( j; j <= cols; j++) {
var col = document.createElement("td");
val = i * j;
col.innerHTML = val;
row.appendChild(col);
}
j = 1;
table.appendChild(row);
}
elem.parentNode.insertBefore(table,elem.nextSibling);
}
addMultiTable(4,8);
function addMultiTable(rows, cols) {
var myHeader = document.getElementsByTagName("h1")[0];
var table = document.createElement("table");
for(i=0; i < rows; i++ ) {
var row = document.createElement("tr");
table.appendChild(row);
for (j = 0; j < cols; j++) {
var cell = document.createElement("td");
cell.innerHTML = (i+1)*(j+1);//value inside cells
row.appendChild(cell);
}
table.appendChild(row);
}
myHeader.appendChild(table);
}
Use jQuery .append() function to append the table to the div.
You can find the demo of the .append() in https://jsfiddle.net/stktjo67/
And Here is the documentation link for .append() http://api.jquery.com/append/

how to add data in a dynamic table

hi i have a table which is created dynamically .this is the code for table creation
function table() {
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
id = 0;
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
}
}
$(".lefttablediv").append(tbl);
};
table();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
now it is empty table i want add different data in each tr how can i add data?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Html>
<body id ="body">
</body>
</html>
<script>
function table() {
var body = document.body;
var tbl = document.createElement('table');
var tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
alert(tbl);
console.log(tbl);
id=0
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode("Please add some text here"));
}
}
$("#body").append(tbl);
};
table();
</script>
td.appendChild(document.createTextNode("")); you are appending blank data which showing blank page add some text it will reflect on page
***** td.appendChild(document.createTextNode("Please add sone text here"))****

How to edit this table responsive script?

I'm using this script to automatically adapt tables to Smartphone view.
It works perfectly! But in some pages, I will have more than one table, and the script seems working only with the first table.
Look at my example, resize your browser window: http://elenatest.altervista.org/index.html
Here's JS code put in the body:
<script type="text/javascript">
var headertext = [],
headers = document.querySelectorAll("#MyTable th"),
tablerows = document.querySelectorAll("#MyTable th"),
tablebody = document.querySelector("#MyTable tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
</script>
Is there a way to make this script running for all the tables in the page?
EDIT
I changed the ID with a CLASS. Here's JS code:
<script type="text/javascript">
var headertext = [],
headers = document.querySelectorAll(".MyTable th"),
tablerows = document.querySelectorAll(".MyTable th"),
tablebody = document.querySelector(".MyTable tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
</script>
And obviously in my HTML:
<table class="MyTable">
<!--etc etc-->
</table>
By selecting "table" first, then apply your function on each:
Array.prototype.slice.call(document.querySelectorAll("table")).forEach(function (table) {
var headertext = [];
var headers = table.querySelectorAll("th");
var tablebody = table.querySelector("tbody");
var i, j, row, col;
for(var i = 0; i < headers.length; i++) {
headertext.push(headers[i].textContent.replace(/\r?\n|\r/,""));
}
for (i = 0; row = tablebody.rows[i]; i++) {
for (j = 0; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
});
As you are using an id #MyTable you assume that you'll have only one table on your page.
First, you should change this to class to be semantically more correct.
Then, you need to iterate on tablebody as you do with headers.
for(var i = 0; i < tablebody.length; i++) {

how to get the textbox value within table in alert message using javascript

This is the table created dynamically using javascript, I want to show this textbox value in alert message using GetCellValues() function.
function makeTable()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab=document.createElement('table');
tab.setAttribute('id','newtable');
tbo=document.createElement('tbody');
tbo.setAttribute('id','tabody');
for(c = 0;c < row_num; c++)
{
row[c]=document.createElement('tr');
for(k = 0; k < cell_num; k++)
{
cell[k] = document.createElement('td');
if (k > 0)
{
cont=document.createElement("input");
cont.setAttribute('type','text');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else
{
cont=document.createTextNode("0" + (c+1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
Please check the GetCellValues() function, this function is not showing the textbox value in alert message.
function GetCellValues()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab = document.getElementsByTagName('table');
tbo = tab.getElementsByTagName('tbody');
for(c = 0;c < row_num; c++)
{
row = tbo.getElementsByTagName('tr');
for(k = 0; k < cell_num; k++)
{
cell = row.getElementsByTagName('td');
{
cont=cell.getElementsByTagName('input');
{
alert(cont.value);
}
}
}
}
}
I think you need some modification in GetCellvalues function as tab.getElementsByTagName('tbody'); will not get elements having tag name tbody for thi you should use document.getElementsByTagName.
you can check working demo of you code here
If you are getting an alert box with [object HTMLCollection] message in it, then you need to use
alert(cont[0].value) in place of alert(cont.value) at the end of your GetCellValues function.
getElementsByTagName returns collection, you need to iterate through it or assume the first element - apply to row, cell, e.g.
var rows = tbo.getElementsByTagName('tr');
for (var c = 0; c < row_num; c++) {
row = rows[c];
var cells = row.getElementsByTagName('td');
for (var k = 0; k < cell_num; k++) {
cell = cells[k];
// and so on
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table id="mytable"></table>
<input type="button" onclick="GetCellValues(20, 4);" value="click me" />
<script type="text/javascript">
function makeTable() {
row = new Array();
cell = new Array();
row_num = 20;
cell_num = 4;
tab = document.createElement('table');
tab.setAttribute('id', 'newtable');
tbo = document.createElement('tbody');
tbo.setAttribute('id', 'tabody');
for (c = 0; c < row_num; c++) {
row[c] = document.createElement('tr');
for (k = 0; k < cell_num; k++) {
cell[k] = document.createElement('td');
if (k > 0) {
cont = document.createElement("input");
cont.setAttribute('type', 'text');
cont.setAttribute('value', '');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else {
cont = document.createTextNode("0" + (c + 1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
makeTable();
function GetCellValues(row_num, cell_num) {
var arrInput = document.getElementsByTagName('input');
var index = (row_num - 1) * (cell_num - 1);
alert(arrInput[index].value);
}
</script>
</body>
</html>
A shortcut approach would be to use ID attribute of tag.
Sample TD tag with ID:
<td id="1_1">1st row 1st column</td><td id="1_2">1st row 2nd column</td>
Javascript to get TD with ID:
var row_len=1,col_len=2;
for (r = 0; r< row_len; r++) {
for (c = 0; c < coll_len; c++) {
alert(document.getElementById(r+'_'+c));
}
}

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