#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    9
    Rep Power
    0

    Create a dynamic table in the body from a function in the head?


    I need to create a dynamic table in the body that I can add data to from a script in the head. Sounds simple enough, but I'm having a lot of trouble finding the right way to do it.

    The closest example of something that does this is the following code I found:

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Untitled Document</title>
    content="text/javascript">
    <style type="text/css">
    .mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    .mytable td{
    background:#cccccc;
    border:1px solid #000000;
    }
    </style>
    
    <script type="text/javascript">
    onload=function(){
    var nrCols=2;
    var maxRows=4;
    var nrRows=maxRows+1;
    while(nrRows>maxRows){
    nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
    }
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    tab.className="mytable";
    var tbo=document.createElement('tbody');
    var row, cell;
    for(var i=0;i<nrRows;i++){
    	row=document.createElement('tr');
    	for(var j=0;j<nrCols;j++){
    		cell=document.createElement('td');
    		cell.appendChild(document.createTextNode(i+' '+j))
    		row.appendChild(cell);
    	}
    	tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
    }
    </script>
    </head>
    <body>
    <div id="mydiv"></div>
    </body>
    </html>
    The problem is that in my actual application I want to call the function from within a loop in the script in the head. The above example uses onload to load the function.

    I tried just turning it into a normal function and calling it from the head but that doesn't seem to work.
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,158
    Rep Power
    184
    Originally Posted by holdorfold1
    I tried just turning it into a normal function and calling it from the head but that doesn't seem to work.
    I don't know why it wasn't working for you; I guess it may have depended on how you had your code set-up. Try this; it should work fine:
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Untitled Document</title>
    <style type="text/css">
    .mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    .mytable td{
    background:#cccccc;
    border:1px solid #000000;
    }
    </style>
    
    <script type="text/javascript">
    function buildIt()
    {
    var nrCols=2;
    var maxRows=4;
    var nrRows=maxRows+1;
    while(nrRows>maxRows){
    nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
    }
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    tab.className="mytable";
    var tbo=document.createElement('tbody');
    var row, cell;
    for(var i=0;i<nrRows;i++){
    	row=document.createElement('tr');
    	for(var j=0;j<nrCols;j++){
    		cell=document.createElement('td');
    		cell.appendChild(document.createTextNode(i+' '+j))
    		row.appendChild(cell);
    	}
    	tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
    }
    </script>
    </head>
    <body>
    <div id="mydiv"></div>
    <button onclick="buildIt()">Add Rows</button>
    </body>
    </html>
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    9
    Rep Power
    0
    Thanks, but the problem is that I need to call the function from the <head> not the <body>.

    The button in that example calls the function from the <body>, but I need to call it from the <head>.

    For instance the following code does not work where I try and call the function from the head:

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Untitled Document</title>
    <style type="text/css">
    .mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    .mytable td{
    background:#cccccc;
    border:1px solid #000000;
    }
    </style>
    
    <script type="text/javascript">
    
    buildIt();            //<------------------------- doesn't work
    
    function buildIt()
    {
    var nrCols=2;
    var maxRows=4;
    var nrRows=maxRows+1;
    while(nrRows>maxRows){
    nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
    }
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    tab.className="mytable";
    var tbo=document.createElement('tbody');
    var row, cell;
    for(var i=0;i<nrRows;i++){
    	row=document.createElement('tr');
    	for(var j=0;j<nrCols;j++){
    		cell=document.createElement('td');
    		cell.appendChild(document.createTextNode(i+' '+j))
    		row.appendChild(cell);
    	}
    	tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
    }
    
    </script>
    
    </head>
    <body>
    <div id="mydiv"></div>
    
    </body>
    </html>
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    9
    Rep Power
    0
    To give context, the following is the actual application that I've made which I need to modify to output data to a table. At the moment I'm just using document.body.innerHTML to write to the page.

    (It's a bit messy, but you can see the document.body.innerHTML output towards the end of the <head>.)

    Code:
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Search for up to 200 places with Radar Search</title>
        <link href="https://developers.google.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
        <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places,visualization&v=3.exp"></script>
        <script>
    var map;
    var infoWindow;
    var service;
    
    function initialize() {
      map = new google.maps.Map(document.getElementById('map-canvas'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(51.412818, -0.301248),
        zoom: 14,
        styles: [
          {
            stylers: [
              { visibility: 'simplified' }
            ]
          },
          {
            elementType: 'labels',
            stylers: [
              { visibility: 'off' }
            ]
          }
        ]
      });
    
      infoWindow = new google.maps.InfoWindow();
      service = new google.maps.places.PlacesService(map);
    
      google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
    }
    
    function performSearch() {
      var request = {
        bounds: map.getBounds(),
        keyword: 'taxi'
      };
      service.radarSearch(request, callback);
    	
    }
    
    function requestInfoWrapper(results, i) {
        i = i + 1;
        if (i >= results.length) {alert('Listing Complete');return};
       
    		ShowResults(results[i]);
        setTimeout(function() {requestInfoWrapper(results, i);}, 500);
    		
    }
    
    function callback(results, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert(status);
            return;
        }
        alert(results.length + ' matches found');
        requestInfoWrapper(results, -1);
    		
    }
    
    function ShowResults(place) {
    
      service.getDetails(place, printme); 
    
    }
    
    function printme(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
      
    	 if (typeof place.reviews !== 'undefined'){
    	 
    	   var xScore = 0;
    	   var xGlobal=0;
    	 
    	   for (var i = 0; i<place.reviews.length; i++) {
             
    		 reviews=place.reviews[i];
    			 
    				 
    	for (var x = 0; x<reviews.aspects.length; x++) {
    		aspectr=reviews.aspects[x];
    		 xScore += aspectr.rating;
    			xGlobal++;
    			 }
      }
    	var xScoreFinal = (xScore/xGlobal);
    				
    			
     }
    	 
    	 if (typeof xScoreFinal !== 'undefined'){
    
      	 document.body.innerHTML += ('<br />'+ '<u>'+place.name+'</u>');
      	 document.body.innerHTML += ('<br />'+'Google Rating: ' + place.rating);
      	 document.body.innerHTML += ('<br />'+ 'The David Score: ' + xScoreFinal);
      	 document.body.innerHTML += ('<br />'+ '<a href = '+place.url +'>'+place.url+'</a>'+'<br />');
    	 }
    	 
      }
    
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
        </script>
      </head>
      <body>
    	 <script>
    	 document.write('DISPLAYING RESULTS');
    	 </script>
       
    	  <div id="map-canvas" style="height:40%; width: 40%; float:left"></div>
        <div style="height:0%; width:0%; float:left">
      </body>
    </html>
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    101
    Rep Power
    27
    Lexical order matters in javascript. You can't invoke buildit() before the function buildit() has been declared and defined.

    Comments on this post

    • web_loone08 agrees
  10. #6
  11. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,158
    Rep Power
    184
    Originally Posted by holdorfold1
    Thanks, but the problem is that I need to call the function from the <head> not the <body>.

    The button in that example calls the function from the <body>, but I need to call it from the <head>.

    For instance the following code does not work where I try and call the function from the head:

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Untitled Document</title>
    <style type="text/css">
    .mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    .mytable td{
    background:#cccccc;
    border:1px solid #000000;
    }
    </style>
    
    <script type="text/javascript">
    
    buildIt();            //<------------------------- doesn't work
    
    function buildIt()
    {
    var nrCols=2;
    var maxRows=4;
    var nrRows=maxRows+1;
    while(nrRows>maxRows){
    nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
    }
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    tab.className="mytable";
    var tbo=document.createElement('tbody');
    var row, cell;
    for(var i=0;i<nrRows;i++){
    	row=document.createElement('tr');
    	for(var j=0;j<nrCols;j++){
    		cell=document.createElement('td');
    		cell.appendChild(document.createTextNode(i+' '+j))
    		row.appendChild(cell);
    	}
    	tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
    }
    
    </script>
    
    </head>
    <body>
    <div id="mydiv"></div>
    
    </body>
    </html>
    You need a window/document/DOM event to trigger the function; you would do it like this..., for an onLoad event:
    Code:
    window.onload = function(){
     buildIt();
    }
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    101
    Rep Power
    27
    WRT your google maps example - if the only issue is how to append data to a <table> from that printme() function... this sort of thing seems to me just so much simpler if you grab a library like jQuery. If you put a table element in your document with an ID, maybe <table id="printTable"></table> then jQuery code to append rows to it is dead simple.
    Code:
    // create a new tr element
    var tr = $("<tr/>");
    // add cells to it
    tr.append($("<td/>").html(place.name));
    tr.append($("<td/>").html(place.rating));
    tr.append($("<td/>").html(xScoreFinal));
    tr.append($("<td/>").html('<a href="'+place.url+'">'+place.url+'</a>'));
    // append tr to table
    $("#printTable tbody").append(tr);
    The table would probably start with a header row giving column titles?
    Code:
    <table id="printTable">
    <thead><tr><th>Name</th><th>Rating</th><th>David's Score</th><th>URL</th></tr></thead>
    <tbody></tbody>
    </table>
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    9
    Rep Power
    0
    Thanks, the Jquery method works perfectly !

    I've also removed the <head> and <body> tags from my code which aren't really needed.
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    101
    Rep Power
    27
    I've also removed the <head> and <body> tags from my code
    Uh.... .... why? Are you rebelling against the opressive weight of fully-formed HTML documents?
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    9
    Rep Power
    0


    Btw, the jquery tables have saved me a lot of trouble.

    I've now run into a different problem though, I'll have to make another thread.

IMN logo majestic logo threadwatch logo seochat tools logo