www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Populating a table from an array.

Hybrid View

  1. #1
    Join Date
    Apr 2012
    Posts
    47

    Question Populating a table from an array.

    I have a simple HTML table with first name, last name as the column headers. I am adding an age column and want to populate the rows with values from an array but am having issues. Here is my code:
    Code:
    <html>
    	<head>
    		<title>Untitled Page</title>
    	</head>
    	<body>
    				<h1>The Seinfeld Family</h1>
    				<table id="Seinfeld Family" bgcolor=#66ffc border="1" style="width:533px;">
    					<tr  bgcolor=#ff0000><th>First Name</th><th>Last Name</th></tr>
    					<tr><td>George</td><td>Constanza</td></tr>
    					<tr><td>Jerry</td><td>Seinfeld</td></tr>
    					<tr><td>Krammer</td><td>Cosmo</td></tr>
    					<tr><td>Elaine</td><td>Benice</td></tr>
    					<tr><td>Larry</td><td>King</td></tr>
    					<tr><td>Bill</td><td>O'Reilly</td></tr>
    				</table>
    				
    				<script type="text/javascript">
    				var table=document.getElementById("Seinfeld Family");
    				//insert allert statements here
    				alert(table.nodeName);
    	            alert(table.childNodes[1].nodeName);
    	            alert(table.childNodes[1].childNodes[0].nodeName);
    	            alert(table.childNodes[1].childNodes[0].childNodes[0].nodeName);
                        alert(table.childNodes[1].childNodes[0].childNodes[0].childNodes[0].nodeName);
    
    				
    				
    				//code to add a new column to the Seinfeld Family table
    				var tableBody=table.getElementsByTagName("TBODY");
    				var tableRows=tableBody[0].getElementsByTagName("TR");
    				var headerRow=tableRows[0];
    				var headerColumns=headerRow.childNodes;
    				
    				alert("Adding column header...");
    				var newColumn=document.createElement('TH');
    				var newColumnText=document.createTextNode("Age");
                                    newColumn.appendChild(newColumnText);
    				headerRow.appendChild(newColumn);
    				
    				//fill in code to add data in the Age column here
    				var ageValues=["36","42","44","56","35","56"];
    				
    				
            			
        
    				//step c)
    				
    				
    				
    				//add ID collumn and generate ID values
    				//step d)
    				alert("Adding column header...");
    				var newColumn=document.createElement('TH');
    				var newColumnText=document.createTextNode("ID");
                                    newColumn.appendChild(newColumnText);
    				headerRow.appendChild(newColumn);
    				
    				</script>
    	</body>
    </html>
    Any help is much appreciated.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444
    Question.

    Why do you hard code some of the table and then add info from an array?

    Why not create the whole table from an array?

  3. #3
    Join Date
    Apr 2012
    Posts
    47
    It's a lab exercise for a class. Just what we have to do I guess. I'm just having trouble with my for loop to populate the "age" and "ID" columns.

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444
    Then this is not the solution for you ...
    Code:
    <html>
    <meta charset="UTF-8">
    <head>
    <title>Untitled Page</title>
    <style type="text/css">
     .tblHead { background-color:#ff0000; font-size:1.2em; font-weight:bold; }
    </style>
    </head>
    <body>
    <h1>The Seinfeld Family</h1>
    <div id="Seinfeld_Family"></div>
    
    <script type="text/javascript">
    var tblValues=[
       "Firstname,Lastname,Age,ID",
       "George,Constanza,36,111",
       "Jerry,Seinfeld,42,222",
       "krammer,Cosmo,44,333",
       "Elaine,Benice,56,444",
       "Larry,King,35,555",
       "Bill,O'Reilly,56,666"
    ];
    var str = '', tarr = [];
    str += '<table bgcolor=#66ffc border="1" style="width:533px;">';
    tarr = tblValues[0].split(',');
    str += '<thead><tr class="tblHead"><td>'+tarr.join('</td><td>')+'</td></tr></thead><tbody>';
    for (var i=1; i<tblValues.length; i++) {
      tarr = tblValues[i].split(',');
      str += '<tr><td>'+tarr.join('</td><td>')+'</td></tr>';
    }
    str += '</tbody></table>';
    document.getElementById('Seinfeld_Family').innerHTML = str;
    </script>
    </body>
    </html>

  5. #5
    Join Date
    Apr 2012
    Posts
    47
    Ha...No it is not. I wish I could do it that way. Thanks though. My for loop looks like this:
    Code:
    var ageValues=["36","42","44","56","35","56"];
              var index=ageValues[index];
    	  for(var index=0; index<ageValues.length; index++){
                   newColumn.appendChild[index];
    	}
    ..but It's obviously wrong.

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444

    Lightbulb

    For sure the line in RED will not work...
    Code:
    var ageValues=["36","42","44","56","35","56"];
    var index=ageValues[index];
    for(var index=0; index<ageValues.length; index++){
      newColumn.appendChild[index];
    }
    You are defining a variable with a variable that is undefined.

  7. #7
    Join Date
    Apr 2012
    Posts
    47
    Yeah....didn't think so. Will my for loop work how it is? I'm sure my newColumn.appendChild line is wrong as well.

  8. #8
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444
    Yeah, it's wrong a written...

    Take a look at this series of articles.
    See if they make sense to you.

    http://www.webreference.com/js/column44/index.html

  9. #9
    Join Date
    Feb 2014
    Location
    Canada
    Posts
    155
    Try the following code. Keep in mind, it assumes all 3 arrays are of the same length. The last row demonstrates to print out array elements that are blank.

    HTML Code:
    <!DOCTYPE html>
    <html>
    	<head>
    		<script type = "text/javascript">			
    			window.onload = function() {
    				var firstNames = ["george", "fred", "john", "sam", ""];
    				var lastNames = ["smith", "guy", "doe", "sly", ""];
    				var ages = [20, 22, 24, 26, null];
    				var table = document.getElementById("theTable").getElementsByTagName("tbody")[0];
    				for(var i = 0; i < firstNames.length; i++) {
    					var newTr = table.insertRow(-1);
    					newTr.insertCell(-1).appendChild(document.createTextNode(firstNames[i]));
    					newTr.insertCell(-1).appendChild(document.createTextNode(lastNames[i]));
    					newTr.insertCell(-1).appendChild(document.createTextNode(ages[i]));
    				}
    			}
    		</script>
    	</head>
    	<body>
    		<table id = "theTable" cellpadding = "3" cellspacing = "3" border = "1">
    			<thead>
    				<tr>
    					<th>First name</th>
    					<th>Last name</th>
    					<th>Age</th>
    				</tr>
    			</thead>
    			<tbody>
    			</tbody>
    		</table>
    	</body>
    </html>

  10. #10
    Join Date
    Apr 2012
    Posts
    47
    Thanks. That definitely works, but I would have to basically start my table from scratch. All I'm trying to do is add an age and ID column to the existing table. I just don't think I'd get credit for doing it like this when my Professor is asking for something different. REALLY appreciate it though.

  11. #11
    Join Date
    Apr 2012
    Posts
    47
    So...I got it. Here are my for loops:
    Code:
    var ageValues=["36","42","44","56","35","56"];
    				
    				for(var i=0; i<ageValues.length; i++){
                                    var newRow=document.createElement('TD');
    				var newRow1=tableRows[i+1];
    				var newRowText=document.createTextNode(ageValues[i]);
    				newRow.appendChild(newRowText);
    				newRow1.appendChild(newRow);
    					}
    				
            			
        
    				//step c)
    				
    				
    				
    				//add ID collumn and generate ID values
    				//step d)
    				alert("Adding column header...");
    				var newColumn=document.createElement('TH');
    				var newColumnText=document.createTextNode("ID");
                                    newColumn.appendChild(newColumnText);
    				headerRow.appendChild(newColumn);
    				
    				var idValues=["1","2","3","4","5","6"];
    				for(var i=0; i<idValues.length; i++){
                                    var newRow=document.createElement('TD');
    				var newRow1=tableRows[i+1];
    				var newRowText=document.createTextNode(idValues[i]);
    				newRow.appendChild(newRowText);
    				newRow1.appendChild(newRow);
    					}
    The only thing I have to do now is move that ID column to the first in the table. Anyone...anyone....Bueller?

  12. #12
    Join Date
    Apr 2012
    Posts
    47
    Awesome, thanks! This looks like exactly what I need. I'll go over this and reply when finished....or stuck again.

  13. #13
    Join Date
    Feb 2014
    Location
    Canada
    Posts
    155
    Quote Originally Posted by Tullamore View Post
    Awesome, thanks! This looks like exactly what I need. I'll go over this and reply when finished....or stuck again.
    No problem, feel free to ask and good luck.

  14. #14
    Join Date
    Feb 2014
    Location
    Canada
    Posts
    155
    I ran your script and nothing loaded, even after putting it inside window.onload = function() {...}. tableRows isn't defined.

  15. #15
    Join Date
    Feb 2014
    Location
    Canada
    Posts
    155
    After mulling over what you wanted, I realized the code is actually pretty short. Try this and see if it does what you need. If you want to move the ages and ID columns to the left-most side of the table, you're going to have to move the contents as well but being lazy, I just added it to the right.

    HTML Code:
    <!DOCTYPE html>
    <html>
    	<head>
    		<script type = "text/javascript">			
    			window.onload = function() {
    				var ages = [20, 22, 24];
    				var tableBody = document.getElementById("theTable").getElementsByTagName("tbody")[0];
    				var tableHead = document.getElementById("theTable").getElementsByTagName("thead")[0];
    				tableHead.rows[0].insertCell(2).innerHTML = "ages";
    				tableHead.rows[0].insertCell(3).innerHTML = "ids";
    				tableHead.style.fontWeight = "bold"; // without this, the 2 added columns are not bold
    				for(var i = 0; i < ages.length; i++) {
    					tableBody.rows[i].insertCell(2).innerHTML = ages[i];
    					tableBody.rows[i].insertCell(3).innerHTML = i;
    				}
    			}
    		</script>
    	</head>
    	<body>
    		<table id = "theTable" cellpadding = "3" cellspacing = "3" border = "1">
    			<thead>
    				<tr>
    					<th>First name</th>
    					<th>Last name</th>
    				</tr>
    			</thead>
    			<tbody>
    				<tr>
    					<td>Row</td>
    					<td>1</td>
    				</tr>
    				<tr>
    					<td>Row</td>
    					<td>2</td>
    				</tr>
    				<tr>
    					<td>Row</td>
    					<td>3</td>
    				</tr>
    			</tbody>
    		</table>
    	</body>
    </html>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles