I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
I am creating a table that creates tr's and td's within a table. The table with loop through a subtraction calculation and create a column of the results from the for loop. When I try to add the next column it does not parse the calculations but continues to perform calculations
for (i=foo; i<bar+1; i++)
{
var tableNode = document.getElementById('tableID');
var trNode = document.createElement('tr');
var trValue = '';
var tdNode = document.createElement('td');
var tdValue = parseFloat(i) + parseFloat(500); //this is calculating 500 and not concatenating 500 for every iteration.
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
tableNode.appendChild(trNode);
trNode.appendChild(tdNode);
}
The goal is to do using a for loop that populates the tr's and td's
1 500
2 500
3 500
This should work:
let foo = 1,
bar = 3;
for (let i = foo; i <= bar; i++) {
var tableNode = document.getElementById("tableID");
let trNode = document.createElement("tr");
let trValue = "";
let tdNode = document.createElement("td");
let tdValue = parseFloat(i) + ' ' + parseFloat(500);
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
trNode.appendChild(tdNode);
tableNode.appendChild(trNode);
}
table tr td {
border: 1px solid #ccc;
}
<table id="tableID"></table>
If you want to concatenate parseFloat(i) and parseFloat(500), do:
var tdValue = parseFloat(i) + " " + parseFloat(500);
instead of parseFloat(i) + parseFloat(500) because this will add the float values and tdValue will be the sum (of type number).
Note the " " (string containing a space) in the middle which will consider the elements to be concatenated as strings and the result of the concatenation to be of type string.
<table> & for loops
If you want to generate a <table> with a for loop you should use two for loops -- first loop is for rows and the second loop is for cells for each row. The following demo has the following:
A <form> that has:
An <input> to enter the number of rows.
An <input> to enter the number of cells per row.
button to trigger the click event that calls the function generateTable().
The <form> and all of its form controls are accessed by using HTMLFormControlsCollection API.
The methods .insertRow() and .insertCell() will automatically create an element and append it.
The <form> and all that's related to it are optional of course, it's just added for demonstration purposes. The loops can be used alone by just assigning numbers to variables rowQty and celQty.
Demo
/*
Optional
*/
var ui = document.forms[0].elements;
var btn = ui.btn;
btn.onclick = generateTable;
/*
Required
*/
function generateTable(e) {
var table = document.getElementById('T0');
/*
if used without the <form>
replace the next two lines with:
*/
//var rowQty = {any integer}
//var celQty = {any integer 2 or greter}
var rowQty = ui.rowData.value;
var celQty = ui.celData.value;
for (let i = 0; i < rowQty; i++) {
var tr = table.insertRow(i);
for (let j = 0; j < celQty; j++) {
var td = tr.insertCell(j);
if (j === 0) {
td.textContent = i + 1;
} else if (j === 1) {
td.textContent = "500";
} else {
td.textContent = " ";
}
}
}
}
table {
border-collapse: collapse;
table-layout: fixed;
}
table,
td {
border: 1px solid #000;
text-align: right;
}
td {
min-width: 3ch;
max-width: 150px;
}
td:first-of-type {
width: 3ch;
text-align: center;
}
input {
display: inline-block;
text-align: center;
width: 5ch;
}
<!-- Optional -->
<form id='ui'>
<label for='rowData'>Rows: </label>
<input id='rowData' type='number' min='1' max='10' value='1'>
<label for='celData'>Cells per Row: </label>
<input id='celData' type='number' min='2' max='10' value='2'>
<button id='btn' type='button'>GO</button>
</form>
<!-- Required -->
<table id='T0'></table>
I am trying to create a separate function that once a table has been generated, a value x and y can be placed within the input and it will highlight the desired cell a certain colour.
My issue arises when I try to select the cell specifically, my code breaks down at
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
//selector function
function SelectCell() {
//grab value from the input x and y
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
//insert the value of x and y into an array retriever
var rowIndex = document.getElementById("valy").value;
var cellIndex = document.getElementById("valx").value;
//*********BREAKS DOWN HERE*******
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
change.style.backgroundColor = "red";
//change color of specific coord
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit1">
<input type="number" id="valx" placeholder="x">
<input type="number" id="valy" placeholder="y">
<input type="submit" id="smit2">
<table id="table">
</table>
I'm not sure you can chain it like this:
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
I think what you want is:
//grab value from the input x and y
var rowIndex = +document.getElementById('valy').value;
var cellIndex = +document.getElementById('valx').value;
// Get reference to the table
var table = document.getElementById('table');
// Get the tr of the table with the index rowIndex
var tr = table.querySelectorAll('tr')[rowIndex];
// Query the selected row for all column elements and select the one at the needed index
var change = tr.querySelectorAll('td')[cellIndex];
NOTE: It's probably best to validate the values in the input before trying to retrieve the DOM element to ensure the code does not break if the user enters a non integer value or a value which is out of bounds
Since I finished it anyway:
Here is a working example
var irow = document.querySelector('#irow');
var icol = document.querySelector('#icol');
var smit1 = document.querySelector('#smit1');
var valx = document.querySelector('#valx');
var valy = document.querySelector('#valy');
var smit2 = document.querySelector('#smit2');
function GenerateTable() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
tbl.setAttribute('class', 'generated');
tbl.appendChild(tblBody);
body.appendChild(tbl);
smit1.disabled = true;
irow.disabled = true;
icol.disabled = true;
smit2.disabled = false;
valx.disabled = false;
valy.disabled = false;
}
function SelectCell() {
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
var rowIndex = valy.value;
var cellIndex = valx.value;
var change = document.querySelector('table.generated tbody').children[rowIndex].children[cellIndex];
change.style.backgroundColor = "red";
}
smit1.addEventListener('click', GenerateTable);
smit2.addEventListener('click', SelectCell);
table.generated td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.width100 {
width: 100%;
}
<body>
<div class="width100">
<input type="number" id="irow" placeholder="rows">
<input type="number" id="icol" placeholder="cols">
<input type="submit" id="smit1">
</div>
<div class="width100">
<input type="number" id="valx" disabled="true" placeholder="x">
<input type="number" id="valy" disabled="true" placeholder="y">
<input type="submit" id="smit2" disabled="true">
</div>
</body>
Get All the data values from the auto generated table and show these values through loop to user by JavaScript alert.I have implemented but it is not showing anything in alert.how i can take the values from these autogenrated text fields.
function myFunction() {
var table = document.getElementById("myTable");
var table1 = document.getElementById("myTable").length;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var textf1 = '<div>FirstName:<input type="text" value="Enter Your Name" id="text1" /></div>';
var textf2 = '<div>LastName:<input type="text" value="Enter Your Surname" id="text2" /></div>';
cell1.innerHTML = textf1;
cell2.innerHTML = textf2;
}
function first(){
var x = document.getElementById("myTable");
var textn = "";
var texts= "";
var i;
var a;
for (i = 0; i < x.length ;i++) {
textn += text1[i].value + "<br>";
}
for (a = 0; i < x.length ;i++) {
texts += text2[i].value + "<br>";
}
alert("First Name:"+textn"Second Name:"+texts);
/*var table1 = document.getElementById("myTable").length;
for(var row = 0; row <= table1;row++ ) {
alert("Hello" + text1.value(i) + "Your Surname Is " + text2.value(i) + " You Have Chosen");
}
/*return myFunction()*/
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/myweb.js">
</script>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable"></table>
<table id="myTable1"></table>
<br>
<div id="first"></div>
<button onclick="myFunction()">Add Your First row</button>
<button onclick="first()">Submit</button>
</body>
</html>
function first(){
var x = document.getElementById("myTable");
var inputElements = x.querySelectorAll('input, select, textarea');
for(var i = 0; i < inputElements.length; i++){
alert(inputElements[i].value);
}
}
alert("First Name:"+textn"Second Name:"+texts);
Missing +
alert("First Name:"+textn+"Second Name:"+texts);
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>