I would have "thought" it would be a simple thing to get the (unformatted) text in each cell of a dynamic table but I have failed to solve this problem. So...I have a table that the user can dynamically load with data. They click an add button to insert a row in a table which includes a delete button per row if they want to turn around and delete it.
The table is inside a form. When they submit the form, I need to read each row and each cell in a row in order to dump it into some format so that the table contents display reasonably well in the email that is sent from the form submission.
So the add row function looks like:
function addRow() {
//add a row to the rows collection and get a reference to the newly added row
var newRow = document.all("mytbl").insertRow();
noRows = noRows+1; //because I was having trouble getting the total number of rows later on so I just declared a global so this was readily available
//add cells (<td>) to the new row and set the innerHTML to contain text boxes
var oCell = newRow.insertCell();
oCell.innerHTML = "<input type='button' value='x' onclick='removeRow(this);'/>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t1'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t2'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t3'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t4'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t5'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t6'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t7'>";
}
function removeRow(src){
/* src refers to the input button that was clicked.
to get a reference to the containing <tr> element,
get the parent of the parent (in this case <tr>)
*/
var oRow = src.parentElement.parentElement;
//once the row reference is obtained, delete it passing in its rowIndex
document.all("acatdog").deleteRow(oRow.rowIndex);
noRows = noRows-1;
}
When the form is ready to be submitted I attempted to get the contents back out as follows:
objval = "";
obj = document.getElementById("mytbl");
for (r=0; r < noRows; r++) {
for (c=1; c<8; c++) {
trow = obj.rows[r];
tcell = trow.cells[c];
cellval = tcell.innerText; //errors out with trow.cells being undefined
if (cellval.length < 1) {
alert("Please complete all columns (name, age, ...) for each table entry.");
return false; //code is inside a validate function and table contents are not validated until submit but if they are okay then I also dump contents to a text field tbllst
}
objval = objval+cellval+"\t";
}
objval = objval+"\n";
}
obj = document.getElementById("tbllst");
obj.value = objval;
I've tried all sorts of syntax for getting at those table cells. I'm obviously still getting the syntax wrong. Any help would be appreciated.
MJS