print table from a defined size array

Asked

Viewed 427 times

3

<table border='1' id="tabela">
    <tbody>
    </tbody>
</table>

would like to print differently

$(document).ready(function(){
    var i =0;
    while(i< 100){
        var resto = i%10;

        if(i%10 == 0){
            $("tbody").append("<tr>"); 
        }
        $("tbody").append("<td>"+i+"</td>"); 
        i++;
        //document.getElementById("tabela").innerHtml += "<tr><td>"+i+"</tr></tr>"; 
        if(i%10 == 0){
            $("tbody").append("</tr>"); 
        } 
    }    
});

actually, I wanted to print that way:

[0][5][10][15][20]

[1][6][11][16][21]

[2][7][12][17][22]

[3][8][13][18][23]

[4][9][14][19][24]

how do I do?

http://jsfiddle.net/8Lnmtusf/

  • If any answer helped you or solved your problem, take a vote and mark it as the correct answer, otherwise give more details about what you tried and the results you got. Always vote and choose the right answers is good practice and helps other users.

2 answers

0


I’m not good with Javascript but getting to this solution, keeping in mind your statement that the table has a specific size:

$(document).ready(function(){
    var i = 0;
    var linha = 0;
    var id = 0;
    var pos = 0;
    while(i < 100){
      if(linha < 10) {
        $("tbody").append("<tr id="+id+"></tr>");
        $("#"+id).append("<td>"+i+"</td>");
        linha++;
        id++;
      } else {
        if(pos==10) {
          pos = 0
        }
        $("#"+pos).append("<td>"+i+"</td>");
        pos++;
      }
      i++;
    }
});

http://jsfiddle.net/n5oc52uh/

0

Use two ties for. The first for will be for the iteration of the lines, and the second for, internal to the first, will iterate the columns.

$(document).ready(function(){
    // De acordo com a pergunta, o número de colunas da tabela é fixo ou pré determinado.
    var numeroDeColunas = 5;

    // O número de elementos do "array".
    var valorMaximo = 100;

    // Obtém o número de linhas.
    var numeroDeLinhas = valorMaximo / numeroDeColunas;

    // Esse laço faz a iteração das linhas.
    for (var i = 0; i < numeroDeLinhas; i++) {
        $("tbody").append("<tr id='linha"+ i +"'></tr>"); 

        // Faz a iteração das colunas.
        for (var j = 0; j < numeroDeColunas; j++) {
            $("#linha"+i).append("<td>"+ i + (5 * j) +"</td>");
        }
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.