www.webdeveloper.com
Results 1 to 9 of 9

Thread: Inputing information into a table.

  1. #1
    Join Date
    Jan 2014
    Posts
    10

    Inputing information into a table.

    I'm trying to make a practice website involving a table of data, in this case albums. Eventually I want to be able to organize the information in alphabetical or numerical order, but for now all I want to do is use JavaScript to take arrays and to create a table with those values. I know I can use XML or JQuery for this, but for now I want to focus on JavaScript. Here's the code:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Highlight Table Example</title>
    	<script>
    function Album(artist,title,year,genre) {
    	this.artist=artist;
    	this.title=title;
    	this.year=year;
    	this.genre=genre;
    
    	this.toHTML = function() {
    		var tableGoodness = "";
    		var x=album;
    		
    		tableGoodness += ("<table border='1'><tr bgcolor='#9acd32'><th>Artist</th><th>Title</th><th>Year</th><th>Genre</th></tr>"
    			+ function() { 
    				for (i=0;i<x.length;i++) {					"<tr><td>" + artist + "</td><td>" + title + "</td><td>" + year + "</td><td>" + "</td></tr>"; }				+ "</table>";			}		});
    		return tableGoodness;
    		document.getElementById("goodTable").innerHTML = tableGoodness;
    	}
    document.getElementById("goodTable").innerHTML = tableGoodness;
    	
    
    var album = [ 	new Album("The Beatles","Sgt. Pepper's Lonely Hearts Club Band","1967","Rock"),
    				new Album("Mastodon","Leviathan","2004","Metal"), 
    				new Album("Minus the Bear","Highly Refined Pirates","2001","Alternative"), 
    				new Album("Dead Kennedys","Plastic Surgery Disasters", "1982","Punk"), 
    				new Album("Snoop Dogg","Doggystyle","1993","Hip hop"), 
    				new Album("Nirvana","Nevermind","1991","Alternative"), 
    				new Album("The Mermen","A Glorious Lethal Euphoria","1994","Rock"), 
    				new Album("Daft Punk","Random Access Memories","2013","Pop"), 
    				new Album("Pelican","Australasia","2003","Metal"), 
    				new Album("Gotye","Making Mirrors","2012","Pop"), 
    				new Album("Metallica","Master of Puppets","1986","Metal"), 
    				new Album("Radiohead","Kid A","2000","Alternative"), 
    				new Album("Hum","You'd Prefer an Astronaut","1994","Alternative"), 
    				new Album("Pretty Lights","A Color Map of the Sun","2013","Electronic")
    				new Album("Massive Attack","Mezzanine","1996","Electronic")
    				new Album("Brother Ali","The Undisputed Truth","2007","Hip hop")
    				new Album("Miles Davis","*****es Brew","1971","Jazz")
    				new Album("Bad Religion","Suffer","1988","Punk")];
    ];
    				
    				
    
    </script>
    </head>
    <body>
    <div id="goodTable">
    
    
    
    </div>
    </body>
    </html>
    Opinions of my musical tastes aside, how can I fix this? I figure one of two ways, either insert the Array by row or assign a value to each column. I think I'm almost there..........

  2. #2
    Join Date
    Jan 2014
    Posts
    10
    Here's the code again, but easier to read:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Highlight Table Example</title>
    	<script>
    function Album(artist,title,year,genre) {
    	this.artist=artist;
    	this.title=title;
    	this.year=year;
    	this.genre=genre;
    
    	this.toHTML = function() {
    		var tableGoodness = "";
    		var x=album;
    		
    		tableGoodness += 
    ("<table border='1'><tr bgcolor='#9acd32'><th>Artist</th><th>Title</th>
    <th>Year</th><th>Genre</th></tr>"
    			+ function() { 
    				for (i=0;i<x.length;i++) {					"
    						<tr><td>" + artist + "</td><td>"
    						 + title + "</td><td>" + year
    						 + "</td><td>" + "</td></tr>"; }				
    						+ "</table>";	
    						}		
    				});
    				return tableGoodness;
    				document.getElementById("goodTable").innerHTML = tableGoodness;
    			}
    		document.getElementById("goodTable").innerHTML = tableGoodness;
    	
    
    var album = [ 	new Album("The Beatles","Sgt. Pepper's Lonely Hearts Club Band","1967","Rock"),
    				new Album("Mastodon","Leviathan","2004","Metal"), 
    				new Album("Minus the Bear","Highly Refined Pirates","2001","Alternative"), 
    				new Album("Dead Kennedys","Plastic Surgery Disasters", "1982","Punk"), 
    				new Album("Snoop Dogg","Doggystyle","1993","Hip hop"), 
    				new Album("Nirvana","Nevermind","1991","Alternative"), 
    				new Album("The Mermen","A Glorious Lethal Euphoria","1994","Rock"), 
    				new Album("Daft Punk","Random Access Memories","2013","Pop"), 
    				new Album("Pelican","Australasia","2003","Metal"), 
    				new Album("Gotye","Making Mirrors","2012","Pop"), 
    				new Album("Metallica","Master of Puppets","1986","Metal"), 
    				new Album("Radiohead","Kid A","2000","Alternative"), 
    				new Album("Hum","You'd Prefer an Astronaut","1994","Alternative"), 
    				new Album("Pretty Lights","A Color Map of the Sun","2013","Electronic")
    				new Album("Massive Attack","Mezzanine","1996","Electronic")
    				new Album("Brother Ali","The Undisputed Truth","2007","Hip hop")
    				new Album("Miles Davis","*****es Brew","1971","Jazz")
    				new Album("Bad Religion","Suffer","1988","Punk")];
    ];
    				
    				
    
    </script>
    </head>
    <body>
    <div id="goodTable">
    
    
    
    </div>
    </body>
    </html>

  3. #3
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Highlight Table Example</title>
    <style>
    body{color:#000;background-color:#fff;font-family:Georgia,'Bookman Old Style',Verdana;font-size:14px;text-align:center;}
    table{background-color:#abc;color:#000;}
    th{background-color:#9acd32;color:#000;}
    td{text-align:center;background-color:#fff;color:#000;}
    </style>
    <script>
    var albums=[
    "The Beatles|Sgt.Pepper's Lonely Hearts Club Band|1967|Rock",
    "Mastodon|Leviathan|2004|Metal", 
    "Minus the Bear|Highly Refined Pirates|2001|Alternative",
    "Dead Kennedys|Plastic Surgery Disasters|1982|Punk",
    "Snoop Dogg|Doggystyle|1993|Hip hop",
    "Nirvana|Nevermind|1991|Alternative",
    "The Mermen|A Glorious Lethal Euphoria|1994|Rock",
    "Daft Punk|Random Access Memories|2013|Pop",
    "Pelican|Australasia|2003|Metal",
    "Gotye|Making Mirrors|2012|Pop",
    "Metallica|Master of Puppets|1986|Metal",
    "Radiohead|Kid A|2000|Alternative",
    "Hum|You'd Prefer an Astronaut|1994|Alternative",
    "Pretty Lights|A Color Map of the Sun|2013|Electronic",
    "Massive Attack|Mezzanine|1996|Electronic",
    "Brother Ali|The Undisputed Truth|2007|Hip hop",
    "Miles Davis|*****es Brew|1971|Jazz",
    "Bad Religion|Suffer|1988|Punk"
    ];
    
    function $(id){return document.getElementById(id);}
    
    function Album(artist,title,year,genre){
    this.artist=artist;
    this.title=title;
    this.year=year;
    this.genre=genre;
    this.toHTML();
    }
    
    Album.prototype.toHTML=function(){
    if(!$('myTab')){
    $('goodTable').innerHTML='<table align="center" id="myTab" border="1" cellspacing="3" cellpadding="5"><tr><th>Artist</th><th>Title</th><th>Year</th><th>Genre</th></tr></table>';
    }
    else{
    var row=$('myTab').insertRow(-1),
        cell1=row.insertCell(0),
        cell2=row.insertCell(1),
        cell3=row.insertCell(2),
        cell4=row.insertCell(3);
    
    cell1.innerHTML=this.artist;
    cell2.innerHTML=this.title;
    cell3.innerHTML=this.year;
    cell4.innerHTML=this.genre;
    }
    }
    
    window.onload=function(){
    for(var i=0; i<albums.length; i++){
    var x=albums[i].split('|');
    new Album(x[0],x[1],x[2],x[3]);
    }
    }
    </script>
    </head>
    <body>
    <div id="goodTable"></div>
    </body>
    </html>
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    sorry use this one

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Highlight Table Example</title>
    <style>
    body{color:#000;background-color:#fff;font-family:Georgia,'Bookman Old Style',Verdana;font-size:14px;text-align:center;}
    table{background-color:#abc;color:#000;}
    th{background-color:#9acd32;color:#000;}
    td{text-align:center;background-color:#fff;color:#000;}
    </style>
    <script>
    var albums=[
    "The Beatles|Sgt.Pepper's Lonely Hearts Club Band|1967|Rock",
    "Mastodon|Leviathan|2004|Metal", 
    "Minus the Bear|Highly Refined Pirates|2001|Alternative",
    "Dead Kennedys|Plastic Surgery Disasters|1982|Punk",
    "Snoop Dogg|Doggystyle|1993|Hip hop",
    "Nirvana|Nevermind|1991|Alternative",
    "The Mermen|A Glorious Lethal Euphoria|1994|Rock",
    "Daft Punk|Random Access Memories|2013|Pop",
    "Pelican|Australasia|2003|Metal",
    "Gotye|Making Mirrors|2012|Pop",
    "Metallica|Master of Puppets|1986|Metal",
    "Radiohead|Kid A|2000|Alternative",
    "Hum|You'd Prefer an Astronaut|1994|Alternative",
    "Pretty Lights|A Color Map of the Sun|2013|Electronic",
    "Massive Attack|Mezzanine|1996|Electronic",
    "Brother Ali|The Undisputed Truth|2007|Hip hop",
    "Miles Davis|*****es Brew|1971|Jazz",
    "Bad Religion|Suffer|1988|Punk"
    ];
    
    function $(id){return document.getElementById(id);}
    
    function Album(artist,title,year,genre){
    this.artist=artist;
    this.title=title;
    this.year=year;
    this.genre=genre;
    this.toHTML();
    }
    
    Album.prototype.toHTML=function(){
    if(!$('myTab')){
    $('goodTable').innerHTML='<table align="center" id="myTab" border="1" cellspacing="3" cellpadding="5"><tr><th>Artist</th><th>Title</th><th>Year</th><th>Genre</th></tr></table>';
    }
    var row=$('myTab').insertRow(-1),
        cell1=row.insertCell(0),
        cell2=row.insertCell(1),
        cell3=row.insertCell(2),
        cell4=row.insertCell(3);
    
    cell1.innerHTML=this.artist;
    cell2.innerHTML=this.title;
    cell3.innerHTML=this.year;
    cell4.innerHTML=this.genre;
    }
    
    window.onload=function(){
    for(var i=0; i<albums.length; i++){
    var x=albums[i].split('|');
    new Album(x[0],x[1],x[2],x[3]);
    }
    }
    </script>
    </head>
    <body>
    <div id="goodTable"></div>
    </body>
    </html>
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  5. #5
    Join Date
    Jan 2014
    Posts
    10
    Did you use a little bit of JQuery? In any case, it works well and looks good. I also see you switched my album array into a variable. In general is better to avoid arrays and just do lists as variables? Once again, thank you Padonak.

  6. #6
    Join Date
    Jan 2014
    Posts
    10
    One thing I'm not clear on:

    Code:
    else{
    var row=$('myTab').insertRow(-1),
        cell1=row.insertCell(0),
        cell2=row.insertCell(1),
        cell3=row.insertCell(2),
        cell4=row.insertCell(3);
    Why insert 'myTab' in row (-1)?

  7. #7
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    1. the -1 index will insert a new row as the last row each time
    2. no jQuery, it's just '$' and it could be 'd' or 'doc' or whatever you like
    3. no need to avoid arrays, it just seemed to be looking simplier without ['','','',] at every line ))
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  8. #8
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    An alternative, but sorting the <table> rows based on their content:

    index.html
    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8" />
    		<title>Inputing information into a table.</title>
    		<style type="text/css">
    
    			TABLE {
    				margin: 0 auto;
    			}
    			TH {
    				cursor: pointer;
    			}
    
    		</style>
    	</head>
    	<body>
    
    		<table id="Albums" border="1"></table>
    
    		<script type="text/javascript">
    
    			(function(titles, album)
    			{
    				var
    					table = document.getElementById('Albums'),
    					base, i, j, k,
    					last_index, last_order;
    
    				base = table.appendChild(document.createElement('thead')).appendChild(document.createElement('tr'));
    				for (i = 0 ; i < titles.length; ++i) {
    					base.appendChild((function(e, index)
    					{
    						e.onclick = function()
    						{
    							var
    								i, j, data = [];
    
    							if (last_index === index) {
    								last_order ^= 1;
    							} else {
    								last_index = index;
    								last_order = 0;
    							}
    							for (i = 0, j = base.getElementsByTagName('tr'); i < j.length; ++i) {
    								data.push({
    									e : j[i],
    									o : j[i].getElementsByTagName('td')[index].innerHTML.toLowerCase()
    								});
    							}
    							data.sort(function(a, b)
    							{
    								return (a.o < b.o ? (last_order ? 1 : -1) : (a.o > b.o ? (last_order ? -1 : 1) : 0));
    							});
    							for (i = 0; i < data.length; ++i) {
    								j = data[i].e.parentNode;
    								j.appendChild(j.removeChild(data[i].e));
    							}
    						};
    						return e;
    					}
    					(document.createElement('th'), i))).innerHTML = titles[i];
    				}
    
    				base = table.appendChild(document.createElement('tbody'));
    				for (i = 0; i < album.length; ++i) {
    					k = base.appendChild(document.createElement('tr'));
    					for (j = 0; j < album[i].length; ++j) {
    						k.appendChild(document.createElement('td')).innerHTML = album[i][j];
    					}
    				}
    
    			}
    			([
    				'Artist', 'Title', 'Year', 'Genre'
    			],[
    				['The Beatles', 'Sgt. Pepper\'s Lonely Hearts Club Band', '1967', 'Rock'],
    				['Mastodon', 'Leviathan', '2004', 'Metal'],
    				['Minus the Bear', 'Highly Refined Pirates', '2001', 'Alternative'],
    				['Dead Kennedys', 'Plastic Surgery Disasters', '1982', 'Punk'],
    				['Snoop Dogg', 'Doggystyle', '1993', 'Hip hop'],
    				['Nirvana', 'Nevermind', '1991', 'Alternative'],
    				['The Mermen', 'A Glorious Lethal Euphoria', '1994', 'Rock'],
    				['Daft Punk', 'Random Access Memories', '2013', 'Pop'],
    				['Pelican', 'Australasia', '2003', 'Metal'],
    				['Gotye', 'Making Mirrors', '2012', 'Pop'],
    				['Metallica', 'Master of Puppets', '1986', 'Metal'],
    				['Radiohead', 'Kid A', '2000', 'Alternative'],
    				['Hum', 'You\'d Prefer an Astronaut', '1994', 'Alternative'],
    				['Pretty Lights', 'A Color Map of the Sun', '2013', 'Electronic'],
    				['Massive Attack', 'Mezzanine', '1996', 'Electronic'],
    				['Brother Ali', 'The Undisputed Truth', '2007', 'Hip hop'],
    				['Miles Davis', '*****es Brew', '1971', 'Jazz'],
    				['Bad Religion', 'Suffer', '1988', 'Punk']
    			]));
    
    		</script>
    
    	</body>
    </html>
    JavaScript: Learn | Validate | Compact | bionoid

  9. #9
    Join Date
    Jan 2014
    Posts
    10
    Thanks Bionoid. I have toyed around with Padonak's code and I was able to insert images before and after each <TH> text node using JavaScript. Each link was supposed to activate a JavaScript function with three parameters called sortTable . This function sorted each column in descending or ascending order. However, I was not able to get the <a href> links working using Padonak's code, whether this being from the codes not being compatible or my own competence.

    I'm trying your code now and attempting to do the same thing but in a different way. Once again I'm having trouble making it work. I think I've almost got it:

    Code:
    	function sortThisIcon() {
    		var tabHead	= document.getElementsByTagName('thead');
    		
    		//get the node for TBODY 
    		var tabHeadRow = oTable.getElementsByTagName('tr')[0];
    
    		//get all the TH nodes
    		var tabHeadCol = oTBody.getElementsByTagName('th');
    
    		//Create a link with an up icon and a down icon with a link sorting the tables.
    		var DOM_a1 = document.createElement("a");
    		var id1 = document.createAttribute = "id";
    		id1.value = "ArtistDescend";
    		var href1 = document.createAttribute = "href";
    		href1.value = "javascript:sortTable('tbody'," + tabHeadCol[i] + ",true)";
    		DOM_a1.setAttributeNode(href1);
    		
    		var DOM_a2 = document.createElement("a");
    		var id2 = document.createAttribute = "id";
    		id2.value = "ArtistAscend";
    		var href2 = document.createAttribute = "href";
    		href2.value = "javascript:sortTable('tbody'," + tabHeadCol[i] + ",false)";
    		DOM_a2.setAttributeNode(href2);
    		
    		
    		var DOM_img1 = document.createElement("img");
    		var src1 = document.createAttribute = "src";
    		src1.value = "down.png";
    		var imgClass = document.createAttribute("class");
    		imgClass.value = "clickable";
    		DOM_img1.setAttributeNode(src1);
    		DOM_img1.setAttributeNode(imgClass);
    
    		
    		var DOM_img2 = document.createElement("img");
    		var src2 = document.createAttribute = "src";
    		src2.value = "up.png";
    		DOM_img2.setAttributeNode(src2);
    		DOM_img2.setAttributeNode(imgClass);
    		
    		DOM_a1.appendChild(DOM_img1);
    		DOM_a2.appendChild(DOM_img2);
    		
    		var makeItWork = document.getElementsByTagName("th");
    		makeItWork.appendChild(DOM_a1);
    		makeItWork.appendChild(DOM_a2);
    		
    
    }
    There are eight different hrefs with eight different id's, ArtistDescend, ArtistAscend, AlbumDescend, AlbumAscend, etc. I don't need to be shown all eight obviously, just one.

    In case you wanted to see sortTable, here is the rest of the code relevant to that though I'm much more interested in the first batch of code working. I want to try to figure out this next batch of code on my own:

    Code:
    function sortCallBack(a,b) {
    	//get the child node of each TR element.
    	var col1 = a.getElementsByTagName("TD")[gbCol];
    	var col2 = b.getElementsByTagName("TD")[gbCol];
    
    	//get text node for each col	
    	var text1 = col1.firstChild.data;
    	var text2 = col2.firstChild.data;
    
    	//we have the text nodes, now do the sorting	
    	if (text1 < text2)
    		return gbAscending ? -1 : 1;
    	else if (text1 > text2)
    		return gbAscending ? 1 : -1;
    	else return 0;
    }
    function sortTable(whichTable, whichCol, sortDir) {
    	//get the table object that has the ID we were given as an argument
    	var oTable = document.getElementById(whichTable);
    	
    	//get the node for TBODY since the node contains all the rows to be sorted
    	var oTBody = oTable.getElementsByTagName('TBODY')[0];
    	
    	//get all of the TR tags
    	var aTRows = oTBody.getElementsByTagName('TR');
    	
    	//store length of TR array
    	var numRows = aTRows.length;
    	
    	gbAscending = sortDir;
    	gbCol = whichCol;
    	
    	//make an array to hold each TR tag
    	var theSortedRows = new Array(numRows);
    	
    	//copy each TR tag into array. Do "deep clone" on
    	//each TR tag so all of child TD tags come along with it.
    	var i;
    	for (i = 0; i < numRows; i++) {
    		theSortedRows[i] = aTRows[i].cloneNode(true);
    		}
    	
    	//now sort the array
    	theSortedRows.sort(sortCallBack);
    	
    	//the array has been sorted.
    	//now, put back all table rows we copied
    	oTable.removeChild(oTBody);
    	
    	//make a new one in its place
    	oTBody = document.createElement("TBODY");
    	oTable.appendChild(oTBody);
    	
    	//now insert all of the sorted TR tags from the sorted array
    	for (i = 0; i < numRows; i++) {
    		oTBody.appendChild(theSortedRows[i]);
    	}
    
    }

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