0

I've tried everything I can find via google and nothing has worked correctly. Output is just a single row with all the contents of the array listed. What I need is a way to write the contents of an array but after 3 cells, automatically start a new line. I'll post the code I've made below as well as the question. (yes this is from an assignment. :( )

//***(8) place the words in the string "tx_val" in a table with a one pixel border,
//***    with a gray backgound. Use only three cells per row. Empty cells should contain
//***    the word "null". Show the table in the span block with id="ans8"

var count = i % 3;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
    out += ("<td>" + txArr[i] + "</td>");
    count++;
    if (count % 3 == 0)
    {
        nrow += "</tr><tr>";
    }
}

document.getElementById('ans8').innerHTML = out + nrow;
4
  • No problem with having assignments posted here, so long as you state that this is the case. However, you could tell us what exactly you are having difficulties with... Commented Apr 26, 2011 at 19:16
  • Can you post a sample output for the array? Commented Apr 26, 2011 at 19:16
  • You don't need the nrow var, just change that line to out += "</tr><tr>" and you're half-way there. Commented Apr 26, 2011 at 19:17
  • Your code doesn't work? Please provide any error messages. Commented Apr 26, 2011 at 19:17

8 Answers 8

1

you need to print the tr's inside the table (annd add a </table>!):

var count = i % 3; // btw. what's this??
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
    out += "<td>" + txArr[i] + "</td>";
    count++;
    if (count % 3 == 0)
        out += "</tr><tr>";
}
out += "</table>";

document.getElementById('ans8').innerHTML = out;
Sign up to request clarification or add additional context in comments.

1 Comment

don't need the nrow variable anymore though; and isn't out reserved (I don't remember)
1

Rather than try to write out the html, try manipulating the dom. It seems much more straightforward to me. Take a look at the following:

var row = table.insertRow(); msdn mdc
var cell = row.insertCell(); msdn mdc
var cellContent = document.createTextNode(txArr[i]); msdn mdc
cell.appendChild(cellContent); msdn mdc

For deciding when to start a new row, just use the modulus operator (% msdn mdc ) against i:

if (i % 3 == 0)
{
    row = table.insertRow()
}

You'd end up with something like this:

var container = document.getElementById("ans8");
var t = container.appendChild(document.createElement("table"));
var row;
txArr.forEach(function (item, i)
{
    if (i % 3 == 0)
    {
        row = t.insertRow()
    }
    row.insertCell().appendChild(document.createTextNode(item));
});

I'll leave a little for you to figure out - border, background color, getting the word "null" in there. It is your homework after all. :-)

Also, for older browsers you'll need to add Array.forEach in yourself.

Comments

0

I prefer using an array over concatination

var html = [];
html.push("<table><tr>");
var i = 0;

for (var k in txArr)
{
    if(i>=3){
      i=0;
      html.push("</tr><tr>");
    }
    html.push("<td>" + txArr[k] + "</td>");
    i++;
}
html.push("</tr></table>");

document.getElementById('ans8').innerHTML = html.join('');

// wrapped in function
function arrayToTable(a,cols){
 var html = [];
    html.push("<table><tr>");
    var i = 0;

    for (var k in a)
    {
        if(i>=cols){
          i=0;
          html.push("</tr><tr>");
        }
        html.push("<td>" + a[k] + "</td>");
        i++;
    }
    html.push("</tr></table>");
    return html.join('')
}
document.getElementById('ans8').innerHTML = arrayToTable(txArr, 3);

Comments

0

It might be a tad easier to accomplish with something like

buffer = "<table>";
for(var r = 0; r < 10; r++){
   buffer += "<tr>";
   for(var c = 0; c < 3 ; c++){
      buffer += "<td>Cell: " + r + ":" + c + "</td>";
   }
   buffer += "</tr>";
}
buffer += "</table>";
 document.getElementById("ans8").innerHTML = buffer;

That would create a table 30 rows long by 3 columns for each row.

Comments

0

you might be assigning values to "count" too early as you don't know what i is yet. and you are not spitting out the value of nrow anywhere... change it to out.

var count;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)

{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
    {
    out += "</tr><tr>";
    }
}

 document.getElementById('ans8').innerHTML = out + nrow;

Comments

0

Basically I would split it up into 3 functions, for readability and maintenance. These functions would consist of creating a cell, a row, and a table. This definitely simplifies reading the code. As I have not tested it, below is an example of what I would do.

function createTableCell(value) {
  return value == null? "<td>NULL</td>":"<td>" + value + "</td>";
}

function createTableRow(array) {
  var returnValue = "";
  for (var i = 0; i < array.length; i++) {
    returnValue = returnValue + createTableCell(array[i]);
  }
  return "<tr>" + returnValue + "</tr>";
}

function arrayToTable(array, newRowAfterNArrayElements) {
  var returnValue = "<table>";
  for (var i = 0; i < array.length; i = i + newRowAfterNArrayElements) {
     returnValue = returnValue + createTableRow(array.split(i, (i + newRowAfterNArrayElements) - 1));
  }
  return returnValue + "</table>";
}

document.getElementById("ans8").innerHTML = arrayToTable(txArr, 3);

In addition this makes your code much more dynamic and reusable. Suppose you have an array you want to split at every 4 element. Instead of hardcoding that you can simply pass a different argument.

Comments

0

Here's a live example of doing this with DOMBuilder, and of using the same code to generate DOM Elements and an HTML String.

Code:

var dom = DOMBuilder.elementFunctions;

function arrayToTable(a, cols) {   
  var rows = [];
  for (var i = 0, l = a.length; i < l; i += cols) {
      rows.push(a.slice(i, i + cols));
  }
  return dom.TABLE({border: 1, bgcolor: 'gray'},
    dom.TBODY(
      dom.TR.map(rows, function(cells) {
        return dom.TD.map(cells);
      })
    )
  );
}

var data = [1, 2, null, 3, null, 4, null, 5, 6];

document.body.appendChild(arrayToTable(data, 3));
document.body.appendChild(
  dom.TEXTAREA({cols: 60, rows: 6},
    DOMBuilder.withMode("HTML", function() {
      return ""+arrayToTable(data, 3);
    })
  )
);

Comments

0

Yes, you can build from scratch...but there's a faster way. Throw a grid at it. The grid will take data in a string, array, json output, etc and turn it into a proper HTML outputted table and will allow you to extend it with sorting, paging, filtering, etc.

My personal favorite is DataTables, but there are numerous others out there.

Once you get proficient, setting one of these up literally takes 5 minutes. Save your brain power to cure world hunger, code the next facebook, etc....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.