0

I have an array of values in Javascript as follows:

var data = {"A", "B", "C", "D", "E", "F", "G", "H", "I" };

How can I generate a 3x3 HTML table like the following

A    B    C

D    E    F

G    H    I
3
  • 4
    have you tried anything? Commented Feb 9, 2011 at 12:40
  • That's not even valid JavaScript... Commented Feb 9, 2011 at 12:45
  • var data = {...} <= object ...var data = [...] <= array Commented Feb 9, 2011 at 12:50

3 Answers 3

2
var data = ["A", "B", "C", "D", "E", "F", "G", "H", "I" ]; // corrected Array syntax

var table = document.createElement("table");
var i = 0;
for (var r = 0; r < 3; r++) {
  var row = table.insertRow(-1);
  for (var c = 0; c < 3; c++) {
    var cell = row.insertCell(-1);
    cell.appendChild(document.createTextNode(data[i++]));
  }
}

document.body.appendChild(table);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for using DOM createElement, and createTextNode. I've seen many programmers take the shortcut using a string and innerHTML. Personally I prefer your approach.
I have this same issue, except 4 columns and undefined number of rows. I like that your answer doesn't use innerHtml, however I can't seem to get it to work. Even when I plug yours into jsfiddle.net nothing shows up. Does the html body need to have a table set up?
Yep, I forgot the argument for insertRow and insertCell. It works now: jsfiddle.net/ekaw7 For your requirements, replace the outer for loop with a while loop, that checks if data is still available, and an additional check before using the data. Example: jsfiddle.net/ekaw7/1
1
var data = ["A", "B", "C", "D", "E", "F", "G", "H", "I" ];
var html = '<table><tr>';
for(var i = 0 ; i<data.length; i++){
    if(i%3 == 0 && i != 0){
       html+= '</tr><tr>'
    }
    html+='<td>'+data[i]+'</td>';
}
html+='</tr></table>';

document.write(html);

3 Comments

that'll leave you an empty row up top
That's the same answer I posted, but you were first.. :)
@jswolf91 nope, coz there's the check i!=0 that avoid the empty row ;)
0

http://jsfiddle.net/DuSP5/ just tried this one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.