Simple JavaScript HTML table generator - javascript

This is JavaScript HTML table generator.
Input (from textarea)
<label> <content> //each line
Order by <label>
I need to input the values like that:
Input Values
or
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
And the output should be :
Example
Here is the problem. I don't have ideas to finish my work, but i try my best to code.Can anyone help me?Please!!
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
// CODE START
// CODE END
}
var out="<table>"; // if the value exist, using table to display
// CODE START
// CODE END
out=out+"</table>"
document.getElementById('out').innerHTML=out; // display the result
}
And the html code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> HW3 </title>
<script type="text/javascript" src="abc.js"></script>
<style type = "text/css">
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td
{
border:1px solid black;
}
</style>
</head>
<body>
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
</body>
</html>

I have create sample based on your requirement.
Please check this code.
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
var uniqueValue = [];
var values = [];
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
if (uniqueValue.indexOf(seq[0]) == -1)
{
uniqueValue.push(seq[0]);
values[uniqueValue.indexOf(seq[0])] = new Array();
}
values[uniqueValue.indexOf(seq[0])].push(seq[1]);
}
var maxLength = 0;
var length = values.length;
for (i = 0; i < length; i++)
{
if(values[i].length > maxLength)
maxLength = values[i].length
}
if (length > 0)
{
var out = "<table>"; // if the value exist, using table to display
for (var i = 0; i <= maxLength; i++)
{
out = out + "<tr>"
for (var j = 0; j < length; j++)
{
if(i==0)
{
out = out+ "<th>"+ uniqueValue[j] +"</th>";
}
else
{
if (values[j][i - 1])
out = out + "<td>" + values[j][i - 1] + "</td>";
else
out = out + "<td></td>";
}
}
out = out + "</tr>"
}
out = out + "</table>"
}
document.getElementById('out').innerHTML=out; // display the result
}
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td, tr th
{
border:1px solid black;
}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
Hope this will help you.

I gave it a try too. This approach should give you the big idea behind the dynamically created DOM elements. I think this is a more production-friendly version of the algorithm, given that only native JS is being used.
The main difference with my approach is that it works entirely with dynamic DOM Elements to build the table instead of static html markup. In some cases it can be easier to read and more flexible, especially if you want to work with tag attributes dynamically. I also managed to reduce the complexity by 1 level. Here's my try at it to make it simple and readable:
document.getElementById("btn").addEventListener("click", function(event) {
progress();
}, false);
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
// Build label->content association
var inputs = {};
for (var i = 0; i<line_num; i++)
{
if (line[i] != "") {
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
var label = seq[0];
var content = seq[1];
if (inputs[label] === undefined) {
inputs[label] = [content];
} else {
inputs[label].push(content);
}
}
}
// For a given MxN table output
var M = Object.keys(inputs).length;
var N = 0; // Unknown for now
var tableElement = document.createElement("table");
tableElement.id = "out";
// Generate header
var headerElement = document.createElement("tr");
for (var label in inputs) {
var tdElement = document.createElement("td");
tdElement.appendChild(document.createTextNode(label));
headerElement.appendChild(tdElement);
// calculate N dimension
var contents = inputs[label].length;
if (N < contents) {
N = contents;
}
}
tableElement.appendChild(headerElement);
// Generate rows
for (var i=0; i<N; i++) {
var trElement = document.createElement("tr");
for (var j=0; j<M; j++) {
var tdElement = document.createElement("td");
var label = Object.keys(inputs)[j];
if (inputs[label].length > i) {
var content = inputs[label][i];
tdElement.appendChild(document.createTextNode(content));
}
trElement.appendChild(tdElement);
}
tableElement.appendChild(trElement);
}
var out = document.getElementById('out');
out.parentNode.removeChild(out);
document.body.appendChild(tableElement); // display the result
}
table {border-collapse:collapse;}
tr,td {border:solid 1px #000;}
td {width:100px;}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label>
<textarea name="txt" rows="20" cols = "40">
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
</textarea>
</label>
<br>
<button id="btn" type="submit">Submit</button>
</form>
<p id= "out"></p>
Hope this helps.
Have a nice one!

Related

Create Recursive Form Elements

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>

using a for loop to create tr's and td's in a table element \\ unable to parse results from td's

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>

Creating a JS function that colors a specific cell

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 text fields data from the html table

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);

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