Load table from saved cookie - javascript

I am trying to work out how to save and load data from tables using cookies.
I have been able to save the data to the cookie, but the load function isn't working.
Any idea on how I can make this work?
Basically, I want the cookie to save the data in the table using the "save" button. Then you can mess about with the table and the "load" button will bring it back to how it looked when it was saved.
<html>
<head>
</head>
<body>
<table style="width:100%" id="myTable">
<tr>
<th>Col 1</th>
<th >Col 2</th>
<th >Col 3</th>
<th>Col 4</th>
</tr>
<tr>
<td contenteditable="true" id="left">-</td>
<td contenteditable="true" id="left">-</td>
<td contenteditable="true">-</td>
<td>-</td>
</tr>
</table>
<p id = "paragraph">
</p>
<button type= "submit" class="button" onclick="addRow()">
Add Row
</button>
<button type= "submit" class="button" onclick="addCol()">
Add Col
</button>
<button type= "submit" class="button" onclick="saveTable()">
Save
</button>
<button type= "submit" class="button" onclick="LoadTable()">
Load
</button>
<script>
function addRow()
{
var table = document.getElementById("myTable");
var endOfRows = table.rows.length; // length of rows
var row = table.insertRow(endOfRows);
var endOfCols = table.rows[0].cells.length; // end of cols
for(var i = 0; i< endOfCols; i++)
{
var cell = row.insertCell(i);
cell.innerHTML = "-";
if( i == endOfCols-1)
{
cell.contentEditable = "false";
}
else
{
cell.contentEditable = "true";
}
if(i > 1)
{
cell.style.textAlign = "right";
}
else
{
cell.style.textAlign = "left";
}
}
}
function addCol()
{
var table = document.getElementById("myTable");
var rowLength = table.rows.length;
var endOfCol = table.rows[0].cells.length;
for(var i = 0; i < rowLength; i++)
{
var firstRow = document.getElementById("myTable").rows[i];
var cell = firstRow.insertCell(endOfCol-1);
cell.contentEditable = "true"
if(i == 0)
{
cell.innerHTML = "-";
cell.style.textAlign = "center";
cell.style.backgroundColor = "black";
cell.style.color = "white";
cell.style.fontWeight = "600";
}
else
{
cell.innerHTML = "-";
}
}
}
function saveTable()
{
var table = document.getElementById("myTable");
var noOfRows = table.rows[0].cells.length; // amount of cols
var noOfCols = table.rows.length;
var data = '';
for(var i = 1; i < table.rows.length; i++)
{
for(var j = 0; j < table.rows[0].cells.length-1; j++)
{
data += table.rows[i].cells[j].innerHTML + ",";
}
}
setCookie("data", data, noOfCols, noOfRows, 60);
alert("Cookie Saved");
}
function setCookie(cname, cvalue, noOfRows, noOfCols, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue +";" + expires + ";path=/";
}
function LoadTable()
{
var table = document.getElementById("myTable");
var rowLength = table.rows.length;
var endOfCol = table.rows[0].cells.length;
var data = getCookie("data");
var array = data.split(',');
var count = 0;
for(var i =1;i<rowLength;i++)
{
for(var j = 0; j < endOfCol-1; j++)
{
table.rows[i].cells[j].innerHTML = array[count];
count++;
}
}
}
function getCookie(cname)
{
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ')
{
c = c.substring(1);
}
if (c.indexOf(name) == 0)
{
return c.substring(name.length, c.length);
}
}
return "";
}
PS. I need to do this where the last column is adding up the numbers from the other columns on that row, so we want to skip this column when adding the data, and also not save whatever is in this cell.

Related

Have Javascript (not JQuery) move table row (TR) up or down, not just the Cell (TD)

Have Javascript (not JQuery) move table row (TR) up or down, not just the block of TD Cells.
Add 2 Rows, then you notice that it just moves the cell down or up when you click the up or down button, but not the entire rows color. The information looks like it all gets moved.
I am using javascript only, so JQuery wont work.
Codepen of working code
https://codepen.io/soljohnston777/pen/zYBrMxL
var activeRow = 0;
function setActiveRow(el) {
var rows = document.getElementById('movingTable').rows;
for (var i = 1; i < rows.length; i++) {
if (rows[i] == el) activeRow = i;
}
}
function moveActiveRow(move) {
var rows = document.getElementById('movingTable').rows;
var oldRow = rows[activeRow].innerHTML;
var newRow = rows[activeRow + move].innerHTML;
rows[activeRow].innerHTML = newRow;
rows[activeRow + move].innerHTML = oldRow;
setActiveRow(rows[activeRow + move]);
}
function moveRow(cell, move) {
// alert("Row index is: " + cell.name);
setActiveRow(cell.parentNode);
moveActiveRow(move);
}
function doSubmit() {
var rows = document.getElementById('movingTable').rows;
var ret = new Array();
for (var i = 0; i < rows.length; i++) {
ret[ret.length] = rows[i].getElementsByTagName('td')[0].innerHTML;
}
return ret.join('|');
}
function AddSection() {
var txtName = document.getElementById("txtName");
AddRow(txtName.value, "1");
txtName.value = "";
};
function AddLesson() {
var txtName = document.getElementById("txtName");
AddRow(txtName.value, "2");
txtName.value = "";
};
function AddRow(name, section) {
var table = document.getElementById("movingTable");
// 1 section , 2 lesson
if (section == "1") {
var row = table.insertRow(-1);
var input1 = document.createElement('input');
input1.type = "hidden";
var input2 = document.createElement('input');
input2.type = "text";
input2.setAttribute("value", name);
input2.setAttribute("name", "section[]");
input2.setAttribute("style", "background-color: #5cffde;");
var inputhidden1 = document.createElement('input');
inputhidden1.type = "hidden";
inputhidden1.setAttribute("name", "section[]");
var inputhidden2 = document.createElement('input');
inputhidden2.type = "hidden";
var input3 = document.createElement('input');
input3.type = "button";
input3.value = "Up";
input3.setAttribute("onclick", "moveRow(this, -1);");
var input4 = document.createElement('input');
input4.type = "button";
input4.value = "Down";
input4.setAttribute("onclick", "moveRow(this, 1);");
var input5 = document.createElement('input');
input5.type = "button";
input5.value = "Remove";
input5.setAttribute("onclick", "Remove(this);");
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
cell1.appendChild(input1);
cell2.appendChild(input2);
cell2.appendChild(inputhidden1);
cell2.appendChild(inputhidden2);
cell3.appendChild(input3);
cell4.appendChild(input4);
cell5.appendChild(input5);
inputhidden1 = "";
inputhidden2 = "";
}
if (section == "2") {
var row = table.insertRow(-1);
var input1 = document.createElement('input');
input1.type = "hidden";
var input2 = document.createElement('input');
input2.type = "text";
input2.setAttribute("value", name);
input2.setAttribute("name", "Lesson[]");
var input3 = document.createElement('input');
input3.type = "button";
input3.value = "Up";
input3.setAttribute("onclick", "moveRow(this, -1);");
var input4 = document.createElement('input');
input4.type = "button";
input4.value = "Down";
input4.setAttribute("onclick", "moveRow(this, 1);");
var input5 = document.createElement('input');
input5.type = "button";
input5.value = "Remove";
input5.setAttribute("onclick", "Remove(this);");
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
cell1.appendChild(input1);
cell2.appendChild(input2);
cell3.appendChild(input3);
cell4.appendChild(input4);
cell5.appendChild(input5);
}
var colors = new Array('#ffffff', '#dddddd', '#aaaaaa', '#888888');
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
doMultiple(rows[i], i, rows[i].className);
}
function doMultiple(row, i, s) {
if (section == "1" || s == "sections") {
row.className = "sections";
} else {
row.style.backgroundColor = colors[i % colors.length];
}
}
}
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = button.parentNode.parentNode;
var name = row.getElementsByTagName("TD")[0].innerHTML;
if (confirm("Do you want to delete this?")) {
//Get the reference of the Table.
var table = document.getElementById("movingTable");
//Delete the Table row using it's Index.
table.deleteRow(row.rowIndex);
}
};
table {
border-collapse: collapse;
table-layout: fixed;
width: 100%;
}
table td {
border: solid 1px #e7e7e7;
width: 100px;
word-wrap: break-word;
}
.sections {
background-color: #5cffde;
}
<table border="1" cellspacing="0" cellpadding="0" id="mTable">
<thead>
<tr>
<td>Section?</td>
<td>Section/Lesson Name</td>
<td>Move Up</td>
<td>Move Down</td>
<td>Delete</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table border="1" cellspacing="0" cellpadding="0" id="movingTable">
</table>
<table width="100" border="1" cellspacing="0" cellpadding="0" id="">
<tfoot>
<td></td>
<td><input type="text" id="txtName" /></td>
<td></td>
<td><input type="button" onclick="AddSection()" value="Add Section" /></td>
<td><input type="button" onclick="AddLesson()" value="Add Lesson" /></td>
</tfoot>
</table>

Unable to generate table after clearing table

I'm working on a project but am stuck on the fact that I'm unable to generate a new table after resetting the previous table.
What I would like to do is to let a user reset the table using the button and then generate another one if needed, and not needing him to reload the page. However, I am unsure why my codes only allow me to reset the table but am unable to generate another table.
Any help on this would be greatly appreciated.
function generate() {
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
myTable.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
var parentElement = removeTab.parentElement;
parentElement.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<table id="generatedTable" onmouseover="mouseOver()" onmouseout="mouseOut()"></table>
You were using the id "generatedTable" in a confusing way, at the same time for the newly generated table and for the table you already had in your html file. And at the end you were removing the wrapper table instead of the newly generated one.
It is maybe easier to understand if you use a target element and add the table in it:
const wrapper = document.getElementById('table-wrapper');
function generate() {
var table = document.createElement('TABLE');
table.id = 'generatedTable';
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
wrapper.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
wrapper.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<div id="table-wrapper"></div>

How to add headers to the table columns on button click

I am generating a dynamic table with headers based on user input, and adding columns on click of button. While adding columns on click i want to add header to the column as well. If i click on AppendColumns button it should add column with header.
Demo:
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function AppendColumns() {
var tableCell = document.getElementById('myTable');
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
try this
I think you missed to assign the value for variable cellCnt in the CreateTable() method.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
thead.id = 'tHead';
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
var Header = ["Label", "Control"];
function AppendColumns() {
var tableCell = document.getElementById('myTable');
var lastIndex = tableCell.rows[0].cells.length-1;
var theader = document.getElementById('tHead');
if(lastIndex % 2 ==1){
theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}else{ theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>

Calculate a new AveValue in TableCell while adding new Columns using JavaScript-not JQuery

I have a <th> header row with a stated class, and one fixed row with a stated class. Both are contenteditable. I'm adding new rows and new columns. I want to calculate the AverageValue in the final cell. I have tried the code on a fixed number of rows and it works, but when I try it this way it is only taking in the number of columns, not the DATA inserted. It is also not recognizing the row DATA. I'm clearly missing a function?!
I'm at the stage where I need an extra pair of eyes.
JavaScript:
func = function() {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function() {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-");
}
}
createCell = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute('placeholder', '' - '');
cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute("placeholder", "-");
cell.appendChild(div); // append DIV to the table cell
}
addColumn = function() {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
}
}
}
HTML:
<table class="tg" id="mytable">
<tr>
<th class="tg-s6z2" contenteditable="true">Student Name</th>
<th class="tg-s6z2" contenteditable="true">Student ID</th>
<th class="tg-s6z2" contenteditable="true">Assignment 1</th>
<th class="tg-s6z2" contenteditable="true">Final Grade</th>
</tr>
<tr>
<td class="tg-031e" contenteditable="true">Student1</td>
<td class="tg-031e" contenteditable="true">StudentNo</td>
<td class="tg-0ord" contenteditable="true"></td>
<td class="tg-0ord" contenteditable="true"></td>
</tr>
</table>
<button id="btnFinalGrade" class="btn btn-action" onClick="func();">Final Grade</button>
<button id="btnaddRow" class="btn btn-action" onclick="addRow();">AddRow</button>
<button id="btnaddColumn" class="btn btn-action" onclick="addColumn();">AddColumn</button>
You were adding a div to td element which was throwing error while executing this line document.getElementById("mytable").rows[j].cells[i].innerHTML
which returns a div element not the text you entered!
No need to add a div, Here is the updated code,
func = function () {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function () {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-","tg-031e");
}
}
createCell = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute('placeholder', '' - '');
//cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute("placeholder", "-");
//cell.appendChild(div); // append DIV to the table cell
}
addColumn = function () {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-031e");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-s6z2");
}
}
}

JavaScript reading data into an array from a dynamic table of textfields

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.
Here is my current HTML code.
<head>
<title>TableTest</title>
<script src="/javascript/func.js"></script>
</head>
<body>
<form>
<div id="Input">
<INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
<INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
<table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">
<th>Select</th>
<th>Text1</th>
<th>Text2</th>
<th>Text3</th>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td><INPUT type="text" name="text1"/></td>
<td><INPUT type="text" name="txt2"/></td>
<td><INPUT type="text" name="txt3"/></td>
</tr>
</table>
</div>
</form>
</body>
Here is my JavaScript file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function gatherData(){
//Tests
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
alert(rowCount);
alert(row);
alert(colCount);
}
I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.
var table = document.getElementById('mainTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var tblData = [];
//Put a RowNumber name and values placeholder for the number of rows we have.
for (r = 0; r < table.rows.length; r++)
{
//Debug
//console.log(" row: ", r);
tblData.push({
name: "RowNumber" + r,
items: []
});
//Get the cells for this row.
var cells = table.rows[r].cells;
//Loop through each column for this row and push the value...
for (c = 0; c < cells.length; c++)
{
var inputElem = cells[c].children[0];
var tmpInputElem;
if (inputElem == null)
{
tmpInputElem = "";
}
else
{
tmpInputElem = inputElem.value
}
//Debug
//console.log(" row-cel: ", r, "-", c, " ", inputElem);
tblData[r].items.push(
{
//Comment out the type for now...
//inputType: inputElem.getAttribute('type'),
inputValue: tmpInputElem
});
}
}
//Debug
//printData(tblData);
I tried to keep it simple, and also jQuery clean, so to speak.
var data = [];
function gatherData() {
var table = document.getElementById('dataTable');
for (r = 1; r < table.rows.length; r++) {
var row = table.rows[r];
var cells = row.cells;
for (c = 0; c < cells.length; c++) {
var cell = cells[c];
var inputElem = cell.children[0];
var isInput = inputElem instanceof HTMLInputElement;
if (!isInput)
return;
var value = inputElem.value;
var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
if (isCheckbox)
value = inputElem.checked;
var rowData = {};
rowData.inputType = inputElem.getAttribute('type');
rowData.inputValue = value;
data.push(rowData);
}
}
}
function startExec() {
gatherData();
for (i = 0; i < data.length; i++) {
console.log(data[i].inputType);
console.log(data[i].inputValue);
}
}
//just wait for the dom to load, and then execute the function for testing
document.addEventListener("DOMContentLoaded", startExec, false);
2nd Revision
function getData() {
var table = document.getElementById('dataTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var data = [];
for (l = 0; l < table.rows[0].cells.length; l++) {
data.push({
items: [],
name: "ColumnNumber" + l
});
}
for (i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
for (c = 0; c < cells.length; c++) {
var inputElem = cells[c].children[0];
data[c].items.push({
inputType: inputElem.getAttribute('type'),
inputValue: inputElem.value
});
}
}
printData(data);
}
function printData(data) {
for (i = 0; i < data.length; i++) {
for (k = 0; k < data[i].items.length; k++) {
console.log(data[i].items[k].inputValue);
}
}
}
document.addEventListener("DOMContentLoaded", getData(), false);
It's great that you're starting off and doing the table manipulation yourself, and I would recommend continuing that, if you want to peak into a bigger codebase I would recommend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.
Is this what you are looking for?
JSFIDDLE
$(document).ready(function(){
$('#Finished').click(function(){
var my_arr=[];
$('td').each(function(){
if ($(this).children().is(':checkbox') )
{
if($(this).children().prop('checked'))
{
my_arr.push($(this).children().val());
}
}else{
my_arr.push($(this).children().val());
}
})
console.log(my_arr);
})
})

Categories

Resources