On Apr 30, 8:02 am, irixd...@gmail. com wrote:
I am trying to create a script to enter the values of an array into a
dynamically generated table 3 columns wide. I have a counter for the
row # that I am using to name/id the row TR node so I an attach 3
cells (3 columns) before attaching the full row to the table. I'm not
sure where the problem is, but in its current form my script doesn't
even generate the first node before stopping with an error. Please let
me know what I'm doing wrong.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/
TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
function startup()
{
colcount = 0;
rowcount = 0;
If you intend these to be global variables, better to declare them
with var outside the function to show that is the clear intent.
var List = new
Array('one','tw o','three','fou r','five','six' ,'seven');
Variables starting with a capital letter are normally reserved for
constructors (just a convention, but good to follow). Also,
initialisers are considered better practice:
var list = ['one','two','th ree','four','fi ve','six','seve n'];
var Count = 7;
tabBody=documen t.getElementsBy TagName("TBODY" ).item(0);
Why is tabBody global? You could also use:
var tabBody=documen t.getElementsBy TagName("TBODY" )[0];
for (var i = 0; i<Count; i++)
{
if (colcount == 0)
{
var row=document.cr eateElement("TR ");
You can also use the more convenient insertRow:
row = tabBody.insertR ow(-1);
which creates the row and inserts it in one statement.
rowcount++;
row.id = rowcount;
Though usually tolerated, an ID attribute starting with a number is
invalid:
<URL:
http://www.w3.org/TR/html4/types.html#type-name >
}
cell = document.create Element("TD");
Consider using:
row.insertCell(-1);
textnode=docume nt.createTextNo de(List[i]);
cell.appendChil d(textnode);
document.getEle mentById(rowcou nt).appendChild (cell);
Firebug gives the following error:
document.getEle mentById(rowcou nt) has no properties
because the element with the id rowcount hasn't been added to the
document yet. But the expression isn't needed anyway since you
already have a reference to that element as "row".
row.appendChild (cell);
colcount++;
if (colcount == 3)
{
tabBody.appendC hild(row);
colcount = 0;
}
}}
Consider something like:
function startup() {
var cell, row;
var colcount = 0;
var list = ['one','two','th ree','four','fi ve','six','seve n'];
var tBody = document.getEle mentsByTagName( "TBODY")[0];
for (var i=0, len=list.length ; i<len; i++) {
if (!(colcount%3)) {
row = tBody.insertRow (-1);
}
cell = row.insertCell(-1);
cell.appendChil d(document.crea teTextNode(list[i]));
++colcount;
}
}
A bit of feature detection and defensive programming would be good too
(e.g test that document.getEle mentsByTagName is supported and that
document.getEle mentsByTagName( "TBODY") returns something before
attempting to access its properties).
--
Rob