Show the number of rows and columns Javascript

2

I want the user to enter the row and column quantity of a table and display its values in the table. But when typing the number of rows and columns in the prompt does not display the table and values.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>

   <style>
    .verde{

        background-color: green;
    }

    .amarelo{
        background-color: yellow;

    }
</style>
 <script>



 function criaTabela(linha,coluna){

conteudo="";
conteudo += "<table border='1'>";
for (i=1;i<=linha;i++){
    conteudo += "<tr>";
    for (j=1; j<=coluna;j++){

        if(j % 2 == 0) {
        conteudo += "<div class='coluna_verde'><td>"+ i +" " + j +"</td></div>";
        }
        else{

            conteudo += "<div class='coluna_amarelo'><td>"+ i +" " + j +"</td></div>";
        }
    }           
    conteudo += "</tr>";
}   
conteudo += "</table>";
document.getElementById("tab").innerHTML=conteudo;
 }

   window.onload=function(){
    do{
         var linha=  prompt("Digite a quantidade de linha");    
        var coluna=  prompt("Digite a quantidade de coluna");   

  criaTabela(linha,coluna);


                 }while (linha != null && coluna !=null );

      console.log("linha"+linha);
       console.log("coluna"+coluna);



     }

    </script>
 </head>

 <body>


<div id="tab"></div>
</body>
</html>
    
asked by anonymous 06.10.2017 / 07:06

1 answer

2

Your code was basically correct. I changed some things:

  • I took <div class='coluna_verde'> from within the table HTML because it is invalid syntax. I passed the class to td .
  • I removed do/while because it is not necessary.
  • edit the class names. CSS and html had different names classe_verde and in CSS only verde .
  • I made the input via prompt to be converted to 'Number' '
  • I joined var in loops to start these variables properly

function criaTabela(linha, coluna) {

  conteudo = "";
  conteudo += "<table border='1'>";
  for (var i = 1; i <= linha; i++) {
    conteudo += "<tr>";
    for (var j = 1; j <= coluna; j++) {

      if (j % 2 == 0) {
        conteudo += "<td class='coluna_verde'>" + i + " " + j + "</td>";
      } else {

        conteudo += "<td class='coluna_amarelo'>" + i + " " + j + "</td>";
      }
    }
    conteudo += "</tr>";
  }
  conteudo += "</table>";
  document.getElementById("tab").innerHTML = conteudo;
}

window.onload = function() {
  var linha = Number(prompt("Digite a quantidade de linha"));
  var coluna = Number(prompt("Digite a quantidade de coluna"));

  criaTabela(linha, coluna);
}
.coluna_verde {
  background-color: green;
}

.coluna_amarelo {
  background-color: yellow;
}

td {
  padding: 5px;
}
<div id="tab"></div>
    
06.10.2017 / 08:27