-3

I have been trying to create a table dynamically based on an array return from another function.

I have 2 array :

var listOfNames = ['a', 'b', 'c'];
var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];

The first array will contain element which will be id of each row.

The second array is the list of columns for each row.

My html looks like this

<table>
  <tbody></tbody>
</table>

and the for loop that I have written looks like this :

for (var i = 0; listOfNames.length < i; i++) {
  var row = $('<tr></tr>');
  $(row).attr('id', listOfNames[i]);

  for (var x = 0; scoreLabels.length < x; x++) {
      var tableHeader = $('<td></td>');
      $(tableHeader).attr('text', scoreLabels[x]);
      $(tableHeader).appendTo(row);      
  } 
$(row).appendTo('table');
}

I have been looking at other posts that teaches the creation of table dynamically with jquery, but to no avail.

Please kindly advice and let me know where i went wrong .

The js fiddle can be found here

http://jsfiddle.net/t16scofy/2

biobirdman
  • 4,060
  • 1
  • 17
  • 15

2 Answers2

1

For-loops...

Just read your for-loops out loud:

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

becomes:

for i - starting at 0 - do ... as long as the length of listOfNames is smaller then i.

I starts at 0. and the length of listOfNames is always larger then 0. It is never smaller. so this for loop will never do ...

Same goes for you inner for-loop

corrected:

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

or if you really want the i after the .length:

for (var i = 0; listOfNames.length > i; i++) {...}
Community
  • 1
  • 1
Pinoniq
  • 1,365
  • 9
  • 13
1

You have a few typos and wrong conditions in both your for loops.

This should do it:

var listOfNames = ['a', 'b', 'c'];

var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];

// If i starts with 0, and you're incrementing it, you obviously want the loop 
// to go until it reaches a bigger value, not the other way round.
for (var i = 0; i < listOfNames.length; i++) {
    var row = $('<tr>', { class: i.toString() });

    // If x starts with 0, and you're incrementing it, you obviously want the loop 
    // to go until it reaches a bigger value, not the other way round.
    for (var x = 0; x < scoreLabels.length; x++) {
        var tableHeader = $('<td>', { text: scoreLabels[x] });

        tableHeader.appendTo(row);
    }

    row.appendTo('table');
}

Demo

emerson.marini
  • 9,331
  • 2
  • 29
  • 46