We help IT Professionals succeed at work.
Get Started

Dynamically adding content to a table, working with nodes in javascript

Black-Scout
Black-Scout asked
on
532 Views
Last Modified: 2012-08-14
I have a question about the same dynamically generated table that has been solved in three posts, but isn't working for me :(

The latest post from "digiby" was solved in late march. Could you please post your final code?  

I have been bouncing around with this "lighthouse" dynamically generated table for hours as well and I have read numerous solved posts but my code doesn't work. I've messed it up so much reading the posts that I don't know where I'm going wrong.

I'll paste the javascript code below. With the very lengthy instructions from the textbook.
I will also post the htm file so you can test with me.

When I preview in FF or in IE the table is empty, it is suppose to load with 10 contributors and a total of $1800 in contributions. I also cannot add nor delete a contributor.

Thanks for taking a look:
//display the total number of contributors in the table cells whose ids are "totalContr" and "totalAmt"
function updateTotals() {
	// within the totalContr table cell, display the length of the amount array
    totalC = document.getElementById("totalContr");
	totalC.innerHTML = amount.length;
	// create a variable name totalContributions and set its intital value to 0
	totalContributions = 0;
	/* create a for loop that loops trhough each entry in the amount array. 
	Each time through the loop increase the value of the totalContributions variable by the amount in the current entry in
	the amount array */
	for (var i=0; i <amount.length; i++) {
	    totalContributions += parseInt(amount[i]);	
	}
	// within the totalAmt table cell, display the value of the totalContributions variable
	document.getElementById("totalAmt").innerHTML = totalContributions;
}

   

//creates the contributors table by adding new table rows for each of the entries in the eight data arrays
function makeTable() {
	//Create a variable named headingRow that references the table row with the id "titleRow".
	//This row contains the titles from the contributors table. 
    var headingRow = document.getElementById("titleRow");
	//Create a second variable named blankRow that references the table row with the id "emptyRow"
	var blankRow = document.getElementById("emptyRow");
	/* Use the cloneNode() method to clone the blankRow node.  
	Set the value of the deep variable to true in order to copy the entire node tree.  Store this document fragment in a
	variable named dataRow.
	*/
	dataRow = blankRow.cloneNode(true);
	/*
	Create a for loop that loops through the entries in the amount array.  For each entry call the addRow() function using
	the value of the counter variable in the for loop as the parameter value in the addRow() function.
	*/
	for (var i=0; i<amount.length; i++) {
	    addRow(i);	
	}
	//Call the updateTotals() function  
	updateTotals();
}



/* a function to add a single row to the contributors table, extracting information from the eight data arrays. addRow() has a single parameter named index equal to the array index number from which data is to be taken. */
function addRow(index) {
	/* Use the cloneNode() method to clone the dataRow document fragment you created in the makeTable() function.  Set the
	value of the deep parameter to true.  Store this document fragment in the variable newRow.*/
    newRow = dataRow.cloneNode(true);	
	/* Change the content of newRow's second child node to the value of the date array using the current index. Change the
	content of newRow's third child node to the ntex string "lastName, firstName" where lastName and firstName are the
	values of the lastName and firstName arrays using the current index. Change the content of newRow's fourth child node to
	the text string "street<br />city, state, zip" where street, city, state, and zip are the current values from the
	street, city, state, and zip arrays. Change the content of newRow's fifth child node to the value of the amount array.
	*/
	newRow.childNodes[3].innerHTML = date[index];
    newRow.childNodes[5].innerHTML = lastName[index] + ", " + firstName[index];
    newRow.childNodes[7].innerHTML = street[index] + "<br>" + city[index] + ", " + state[index] + zip[index];
    newRow.childNodes[9].innerHTML = amount[index];
	/*  If the value of the index variable equals 0, meaning that this is the first row being added to the contributor
	table, then use the replaceChild() method to replace the blankRow node with newRow.  (Hint: Apply the replaceChild()
	method to the blankRow.parentNode node)  If the index variable is not equal to 0, then insert the newRow node before the
	next sibling of the headingRow node. (Hint: Apply the insertBefore() method to the headingRow.parentNode node)    */
	if (index == 0) { 
	    blankRow.parentNode.replaceChild(newRow, blankRow) 
	}
    else { 
	    headingRow.parentNode.insertBefore(newRow, headingRow.nextSibling)  
	}
	
}

// a function to create a new contributor record based on the values entered by the user in the web form
function addRecord() {
	// Create a variable named recordNum equal to the length of the amount array.
    recordNum = amount.length;
	/*
	Set the value of first[recordNum] to the value of the fname field from the donations Web form.  
	Set the value of last[recordNum] to the value of the lname field.  
	Set the value of the street array item to the value of the street field
	set the value of the city array item to the value of the city field.  
	Determine which state option has been selected by the user and store the text of the selected option in the state arry
	item. 
	Set the value of the zip, amount, and date array items to the values of the zip, amount, and date fields in the
	donations Web form.  
	*/
	firstName[recordNum] = document.getElementById("fname").value;
	lastName[recordNum] = document.getElementById("lname").value;
	street[recordNum] = document.getElementById("street").value;
	city[recordNum] = document.getElementById("city").value;
	state[recordNum] = document.getElementById("state").value;
	zip[recordNum] = document.getElementById("zip").value;
	amount[recordNum] = document.getElementById("amount").value;	
	date[recordNum] = document.getElementById("date").value;
	//Call the addRow() function using the value of the recordNum variable as the parameter value.
	addRow(recordNum);
	//Call the updateTotals() function.   
	updateTotals();
	
}

/*a funtion to remove a record from each of the eight data arrays. the function has a single parameter "index" that indicates the array item to remove */
function removeRecord(index) {
	/* Use the splice() method to remove the item from the firstName array whose index value equals the value of the index
	parameter.  Remove only one array item.
	*/
	firstName.splice(index,1);
	// Repeat step for the lastName, street, city, state, zip, amount, and date arrays. 
	lastName.splice(index,1);
	street.splice(index,1);
	city.splice(index,1);
	state.splice(index,1);
	zip.splice(index,1);
	amount.splice(index,1);
	date.splice(index,1);
}
 

/* a function whose purpose is to remove a node from a node tree and then return a reference to the node's previious siblings. The single parameter "node" represents the ode hyou want to remove */
function removeNode(node) {
	// Create a variable named prevNode referencing the node's previous sibling. 
	var prevNode = node.previousSibling;
	//Use the removeChild() method to remove the node.  (Hint: Apply the removeChild() method to the node's parent node.)
	prevNode.parentNode.removeChild(prevNode);
	//Return the prevNode variable from the function.      
	return prevNode;
}
 
  
/* Create the removeRecords() function, whose purpose is to remove contributor records from the contributor table and the eight data arrays if the check box for the record has been checked in the contributor table. */
function removeRecords() {
	//  Create a variable named headerRow referencing the row with the id "titleRow".  
	var headerRow;
	ctable.document.getElementById("titleRow") = headerRow;
	// Create a variable named recordNum equal to the length of the amount array.
	var recordNum = amount.length;
	/* Create a for loop that uses familial references, starting with the node variable, n, equal to the first sibling of
	the headerRow node and proceeding to the next sibling (the next table row) until there is no next sibling.
	Within the for loop, decrease the value of the recordNum varialbe by 1.  
	Then, insert an if condition that tests whether the name of the current node is "TR" (a table row).  
	If it is, insert a second if condition that tests whether the check box within the first table cell of the current ro
	has been selected.  (Hint: Reference the check box using the reference n.firstChild.firstChild.)  
	*/
	for ( n = 0; n < headerRow.childNodes.length; n++) {
	recordNum = recordNum - 1;
	if (headerRow.childNodes[n].name = "TR") {
	/*  If the check box has been checked, then: (1) Call the removeRecord() function using the recordNum as the parameter
	value, and (2) Let the node counter, n, be equal to the value returned by the removeNode() function using the n as the
	parameter value. */
  	if (n.firstChild.firstChild != "") {
    removeRecord(recordNum);
	n = removeNode(n)};
	};
	//After the for loop has finished, call the updateTotals() function to update the contribution totals in the Web page.
	updateTotals(); }
}

Open in new window

//display the total number of contributors in the table cells whose ids are "totalContr" and "totalAmt"
function updateTotals() {
	// within the totalContr table cell, display the length of the amount array
    totalC = document.getElementById("totalContr");
	totalC.innerHTML = amount.length;
	// create a variable name totalContributions and set its intital value to 0
	totalContributions = 0;
	/* create a for loop that loops trhough each entry in the amount array. 
	Each time through the loop increase the value of the totalContributions variable by the amount in the current entry in
	the amount array */
	for (var i=0; i <amount.length; i++) {
	    totalContributions += parseInt(amount[i]);	
	}
	// within the totalAmt table cell, display the value of the totalContributions variable
	document.getElementById("totalAmt").innerHTML = totalContributions;
}

   

//creates the contributors table by adding new table rows for each of the entries in the eight data arrays
function makeTable() {
	//Create a variable named headingRow that references the table row with the id "titleRow".
	//This row contains the titles from the contributors table. 
    var headingRow = document.getElementById("titleRow");
	//Create a second variable named blankRow that references the table row with the id "emptyRow"
	var blankRow = document.getElementById("emptyRow");
	/* Use the cloneNode() method to clone the blankRow node.  
	Set the value of the deep variable to true in order to copy the entire node tree.  Store this document fragment in a
	variable named dataRow.
	*/
	dataRow = blankRow.cloneNode(true);
	/*
	Create a for loop that loops through the entries in the amount array.  For each entry call the addRow() function using
	the value of the counter variable in the for loop as the parameter value in the addRow() function.
	*/
	for (var i=0; i<amount.length; i++) {
	    addRow(i);	
	}
	//Call the updateTotals() function  
	updateTotals();
}



/* a function to add a single row to the contributors table, extracting information from the eight data arrays. addRow() has a single parameter named index equal to the array index number from which data is to be taken. */
function addRow(index) {
	/* Use the cloneNode() method to clone the dataRow document fragment you created in the makeTable() function.  Set the
	value of the deep parameter to true.  Store this document fragment in the variable newRow.*/
    newRow = dataRow.cloneNode(true);	
	/* Change the content of newRow's second child node to the value of the date array using the current index. Change the
	content of newRow's third child node to the ntex string "lastName, firstName" where lastName and firstName are the
	values of the lastName and firstName arrays using the current index. Change the content of newRow's fourth child node to
	the text string "street<br />city, state, zip" where street, city, state, and zip are the current values from the
	street, city, state, and zip arrays. Change the content of newRow's fifth child node to the value of the amount array.
	*/
	newRow.childNodes[3].innerHTML = date[index];
    newRow.childNodes[5].innerHTML = lastName[index] + ", " + firstName[index];
    newRow.childNodes[7].innerHTML = street[index] + "<br>" + city[index] + ", " + state[index] + zip[index];
    newRow.childNodes[9].innerHTML = amount[index];
	/*  If the value of the index variable equals 0, meaning that this is the first row being added to the contributor
	table, then use the replaceChild() method to replace the blankRow node with newRow.  (Hint: Apply the replaceChild()
	method to the blankRow.parentNode node)  If the index variable is not equal to 0, then insert the newRow node before the
	next sibling of the headingRow node. (Hint: Apply the insertBefore() method to the headingRow.parentNode node)    */
	if (index == 0) { 
	    blankRow.parentNode.replaceChild(newRow, blankRow) 
	}
    else { 
	    headingRow.parentNode.insertBefore(newRow, headingRow.nextSibling)  
	}
	
}

// a function to create a new contributor record based on the values entered by the user in the web form
function addRecord() {
	// Create a variable named recordNum equal to the length of the amount array.
    recordNum = amount.length;
	/*
	Set the value of first[recordNum] to the value of the fname field from the donations Web form.  
	Set the value of last[recordNum] to the value of the lname field.  
	Set the value of the street array item to the value of the street field
	set the value of the city array item to the value of the city field.  
	Determine which state option has been selected by the user and store the text of the selected option in the state arry
	item. 
	Set the value of the zip, amount, and date array items to the values of the zip, amount, and date fields in the
	donations Web form.  
	*/
	firstName[recordNum] = document.getElementById("fname").value;
	lastName[recordNum] = document.getElementById("lname").value;
	street[recordNum] = document.getElementById("street").value;
	city[recordNum] = document.getElementById("city").value;
	state[recordNum] = document.getElementById("state").value;
	zip[recordNum] = document.getElementById("zip").value;
	amount[recordNum] = document.getElementById("amount").value;	
	date[recordNum] = document.getElementById("date").value;
	//Call the addRow() function using the value of the recordNum variable as the parameter value.
	addRow(recordNum);
	//Call the updateTotals() function.   
	updateTotals();
	
}

/*a funtion to remove a record from each of the eight data arrays. the function has a single parameter "index" that indicates the array item to remove */
function removeRecord(index) {
	/* Use the splice() method to remove the item from the firstName array whose index value equals the value of the index
	parameter.  Remove only one array item.
	*/
	firstName.splice(index,1);
	// Repeat step for the lastName, street, city, state, zip, amount, and date arrays. 
	lastName.splice(index,1);
	street.splice(index,1);
	city.splice(index,1);
	state.splice(index,1);
	zip.splice(index,1);
	amount.splice(index,1);
	date.splice(index,1);
}
 

/* a function whose purpose is to remove a node from a node tree and then return a reference to the node's previious siblings. The single parameter "node" represents the ode hyou want to remove */
function removeNode(node) {
	// Create a variable named prevNode referencing the node's previous sibling. 
	var prevNode = node.previousSibling;
	//Use the removeChild() method to remove the node.  (Hint: Apply the removeChild() method to the node's parent node.)
	prevNode.parentNode.removeChild(prevNode);
	//Return the prevNode variable from the function.      
	return prevNode;
}
 
  
/* Create the removeRecords() function, whose purpose is to remove contributor records from the contributor table and the eight data arrays if the check box for the record has been checked in the contributor table. */
function removeRecords() {
	//  Create a variable named headerRow referencing the row with the id "titleRow".  
	var headerRow;
	ctable.document.getElementById("titleRow") = headerRow;
	// Create a variable named recordNum equal to the length of the amount array.
	var recordNum = amount.length;
	/* Create a for loop that uses familial references, starting with the node variable, n, equal to the first sibling of
	the headerRow node and proceeding to the next sibling (the next table row) until there is no next sibling.
	Within the for loop, decrease the value of the recordNum varialbe by 1.  
	Then, insert an if condition that tests whether the name of the current node is "TR" (a table row).  
	If it is, insert a second if condition that tests whether the check box within the first table cell of the current ro
	has been selected.  (Hint: Reference the check box using the reference n.firstChild.firstChild.)  
	*/
	for ( n = 0; n < headerRow.childNodes.length; n++) {
	recordNum = recordNum - 1;
	if (headerRow.childNodes[n].name = "TR") {
	/*  If the check box has been checked, then: (1) Call the removeRecord() function using the recordNum as the parameter
	value, and (2) Let the node counter, n, be equal to the value returned by the removeNode() function using the n as the
	parameter value. */
  	if (n.firstChild.firstChild != "") {
    removeRecord(recordNum);
	n = removeNode(n)};
	};
	//After the for loop has finished, call the updateTotals() function to update the contribution totals in the Web page.
	updateTotals(); }
}

Open in new window

<html>
<head>
<!-- 
 
   Filename:         clist.htm
   Supporting files: data.js, lhouse.css, logo.jpg, newdata.js

-->
<title>The Lighthouse</title>
<link href="lhouse.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="data.js"> </script>
<script type="text/javascript" src="newdata.js"> </script>
</head>

<body onLoad="makeTable();">
<form name="donations" id="donations" action="">
<div id="title">
   <img src="logo.jpg" alt="The Lighthouse" />
   The Lighthouse<br />
   543 Oak Street<br />
   Delphi, KY &nbsp;&nbsp;89011<br/>
   (542) 555-7511
</div>

<div id="data_entry">
   <table>
   <tr>
      <td>Contributors</td>
      <td id="totalContr"></td>
   </tr>
   <tr>
      <td>Total</td>
      <td id="totalAmt"></td>
   </tr>
   </table>

   <table>
   <tr><td colspan="2"><h3>Enter a New Contributor</h3></td></tr>
   <tr>
      <td>First Name</td><td><input name="fname" id="fname" /></td>
   </tr>
   <tr>
      <td>Last Name</td><td><input name="lname" id="lname" /></td>
   </tr>
   <tr>
      <td>Street</td><td><input name="street" id="street" /></td>
   </tr>
   <tr>
      <td>City</td><td><input name="city" id="city" /></td>
   </tr>
   <tr>
      <td>State</td>
      <td><select name="state" id="state">
      <option>AL</option><option>AK</option><option>AZ</option><option>AR</option>
      <option>CA</option><option>CO</option><option>CT</option><option>DE</option>
      <option>DC</option><option>FL</option><option>GA</option><option>HI</option>
      <option>ID</option><option>IL</option><option>IN</option><option>IA</option>
      <option>KS</option><option>KY</option><option>LA</option><option>ME</option>
      <option>MD</option><option>MA</option><option>MI</option><option>MN</option>
      <option>MS</option><option>MO</option><option>MT</option><option>NE</option>
      <option>NV</option><option>NH</option><option>NJ</option><option>NM</option>
      <option>NY</option><option>NC</option><option>ND</option><option>OH</option>
      <option>OK</option><option>OR</option><option>PA</option><option>RI</option>
      <option>SC</option><option>SD</option><option>TN</option><option>TX</option>
      <option>UT</option><option>VT</option><option>VA</option><option>WA</option>
      <option>WV</option><option>WI</option><option>WY</option>
      </select>
      </td>
   </tr>
   <tr>
      <td>Zip</td><td><input name="zip" id="zip" /></td>
   </tr>
   <tr>
      <td>Amount</td><td><input name="amount" id="amount" /></td>
   </tr>
   <tr>
      <td>Date</td><td><input name="date" id="date" /></td>
   </tr>
   <tr>
      <td colspan="2" id="buttoncell1">
         <input type="button" value="Add Contributor" onClick="addRecord()" />
      </td>
   </tr>
   </table>
</div>

<div id="report">
   <p><input value="Remove Checked Items" type="button" onClick="removeRecords()" /></p>

   <table id="ctable">
   <tr><th colspan="5">Contributor List</th>
   </tr>
   <tr id="titleRow">
      <th>Remove</th>
      <th>Date</th>
      <th>Name</th>
      <th>Address</th>
      <th>Amount</th>
   </tr><tr id="emptyRow"><td class="rc"><input type="checkbox" /></td><td></td><td></td><td></td><td class="ac"></td></tr>
   </table>
</div>

</form>
</body>
</html>

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Top Expert 2015
Commented:
This problem has been solved!
Unlock 3 Answers and 31 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE