Search code examples
javascripthtmldomtidesdk

Convert javascript arrays into HTML table using DOM


I am currently creating a desktop app using tide sdk. All of my database information is stored into Parse.com (a serverless database). What I am trying to do is to take the array of the information I queried from Parse (in javascript) and insert it into a table. I am really having a hard time getting used to not using document.write() for my desktop application.


I want the end result to look like:

table


This is what I started with:

var contactNameArray = [];
var contactNumberArray= [];
var CM = Parse.Object.extend("ContactMenu");
var queryContact = new Parse.Query(CM);
queryContact.ascending("ContactName");
queryContact.find({
  success: function(results4) {
    alert("Successfully retrieved " + results4.length + " entries.");
    // Do something with the returned Parse.Object values
// document.write('<table border="1" cellspacing="1" cellpadding="5">');
    for (var i = 0; i < results4.length; i++) {
      var object4 = results4[i];
      contactNameArray[i] = object4.get('ContactName');
      contactNumberArray[i] = object4.get('ContactNumber');
 // document.write("<tr><td>Number " + i + " is:</td>");
  //document.write("<td>" + contactNameArray[i] + "</td></tr>");

    }

//document.write('</table>');
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

After doing some research I cam upon this bit of code from http://www.w3schools.com/jsref/dom_obj_table.asp which wrote: the correct response on the bottom of the left handed corner of the screen. (Kind of strange in my opinion). In code how can I better position this table to be in the center for my screen? Is there a way to center this table in javascript?

function generate_table() {
 var x = document.createElement("TABLE");
    x.setAttribute("id", "myTable");
    document.body.appendChild(x);

    var y = document.createElement("TR");
    y.setAttribute("id", "myTr");
    document.getElementById("myTable").appendChild(y);
    var z = document.createElement("TD");

    for(var i = 0; i< query4.length; i++){

       var t = document.createTextNode(contactNameArray[i]);
       z.appendChild(t);
       var m = document.createTextNode(contactNumberArray[i]);
       z.appendChild(m);
    }
    document.getElementById("myTr").appendChild(z);
}

So I have already figured out how to put the information I want into an array. I am just having a hard time putting this information into a table that is correctly positioned. Thank you in advance. If you need to see any more of my code, then just let me know. If I am unclear, please let me know what I should explain. Thank you!!!


Solution

  • There are several ways to do this. But from what you already have the simplest is to use innerHTML:

    queryContact.find({
      success: function(results4) {
        var html = "";
        alert("Successfully retrieved " + results4.length + " entries.");
        // Do something with the returned Parse.Object values
        html += '<table border="1" cellspacing="1" cellpadding="5">';
        for (var i = 0; i < results4.length; i++) {
          var object4 = results4[i];
          contactNameArray[i] = object4.get('ContactName');
          contactNumberArray[i] = object4.get('ContactNumber');
          html += "<tr><td>Number " + i + " is:</td>";
          html += "<td>" + contactNameArray[i] + "</td></tr>";
    
        }
    
        html += '</table>';
        document.body.innerHTML += html;
      },
      error: function(error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
    

    As for centering the table on the page the best way is to use CSS. Unfortunately centering anything in CSS is a bit of a hack. There are several ways to do it. See the answers to this question for all the ways of doing it: How to horizontally center a <div> in another <div>?. Note: scroll through the answers, not just read the top one. There really are a lot of ways to do this and some may not work for you.

    A few notes about innerHTML:

    1. Although innerHTML looks like a variable it actually behaves more like a function. Specifically it invokes the HTML compiler of the browser. So if you pass it incomplete tags like:

      someDiv.innerHTML += '<table>';
      

      it will see that as an incomplete 'table' tag and deals with it the way the browser usually does when it sees an incomplete 'table' tag. For some browsers that means removing the table from the DOM. For others that means immediately inserting a closing </table> tag to make it valid. What this means is that when you later append the closing tag like this:

      someDiv.innerHTML += '</table>';
      

      what happens is that the browser will think you did this:

      <table></table></table>
                ^       ^
                |       |_________ what you're trying to insert
                |
         auto inserted by the browser earlier
      

      and deal with it the way browsers usually do - consider that tag invalid and discard it.

      So you need to pass innerHTML well-formed html which is why I created the table structure in a string then append it to the DOM with innerHTML.

    2. A lot of people consider innerHTML stylistically bad since you're doing DOM manipulation with strings. Also because innerHTML was not originally part of any standard and was a proprietary feature of IE. Since it's not part of any standard there's no real agreement between different browsers for how it should work. Having said that, it's probably the most cross-bowser compatible method of manipulating DOM because it's the most widely implemented (even on really old browsers).

      Read the documentation of the DOM API for more info on how to do it "properly": https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

    3. As mentioned by others in the comment to your question, there are also libraries out there that would make your life easier for DOM manipulation. There are procedural libraries like jQuery that wraps the often clunky DOM API and cross-browser issues into a nice to use API. There are also templating library like handlebars that allows you to write the HTML fragments as templates to be processed and inserted into the DOM.

    I suggest getting comfortable with how the DOM works by reading the DOM documentation and follow some tutorial and also look at DOM manipulation libraries like jQuery or YUI or underscore to get a better feel of javascript.

    Paraphrasing Douglas Crockford, you wouldn't start to program in C or Java without learning the language first. Similarly javascript is a full-featured language. Take some time to learn it and not just assume that "it works like [insert a language you know]". There are many features of javascript like closures and asynchronous functions that will trip you up. Similarly the DOM has many behaviors that may work differently from your assumptions of how HTML works.

    But it is a lot to take in. So for now use innerHTML with care being aware of its limitations. Also look at document.getElementById() which is the second most used DOM API for beginners. It allows you to insert your html anywhere in the document using innerHTML. Not just the end of the document.