Ata Utku Orhan Ata Utku Orhan - 2 months ago 10
Javascript Question

How do i make a website that creates a html table using javascript prompts?

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">

var r = prompt ("how many rows ?");
var c = prompt ("how many columns ?");
var red = prompt ("how red ?");
var green = prompt ("how green ?");
var blue = prompt ("how blue ?");
document.write('<table style="width:100%" bgcolor="'+red+''+green+''+blue+'">');
for(var r = i; i > -1; i--){
document.write('<tr>');
for(var c = i; i > -1; i--){
document.write('<th></th>');
};
document.write('</tr>');
};
document.write('</table>');

</script>
</head>
<body>

</body>
</html>


What is wrong with my code ? I answer all the prompts but nothing happens on the screen. My professor said that i would need a for loop inside of an another for loop, what am i missing?

Answer

Multiple corrections:

  1. Don't use document.write multiple times, since each call will overwrite the contents of the body.
  2. Your iterator assignment logic was backwards - assign i = r, not r = i, since the value of the expression (variable in this case) on the right side gets assigned to the variable on the left side.
  3. You need to use a separate iterator variable (e.g. j) for the inner for loop, otherwise it would interfere with the outer loop.
  4. The iterator conditions are off by 1. If you are going to decrement from the max number (of rows, columns) then iterate while i/j are greater than 0, not -1

    var r = prompt ("how many rows ?");
    var c = prompt ("how many columns ?");
    var red = prompt ("how red ?");
    var green = prompt ("how green ?");
    var blue = prompt ("how blue ?");
    var html = '<table style="width:100%"    bgcolor="'+red+''+green+''+blue+'">';  
    for(var i= r; i > 0; i--){        
      html += '<tr>';
        for(var j = c; j > 0; j--){
            html +='<th></th>';
        };
        html += '</tr>';
    };
    html +='</table>';
    document.write(html);
   //or else instead of document.write, use something like the line below :       
   //document.body.innerHTML = html;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body id="container">

</body>
</html>