Jhon Dhoe
Jhon Dhoe

Reputation: 43

How do I display input column table rows through Javascript?

I'm trying to write a program that will give my Table element appropriate column and rows I was able to do the rows part but I get stuck on columns, what is my code not working?

<body>
    <table>
        <script>
            var c = parseInt(prompt("Enter column ")) // 10
            var r = parseInt(prompt("Enter column ")) // 10

            while (0 < c) {
                c--;
                document.write("<td style></td>")
            }

            var r = parseInt(prompt("Enter row "))
            while (0 < r) {
                r--;
                document.write("<tr></tr>")
            }
        </script>
    </table>
</body>

Upvotes: 0

Views: 1905

Answers (2)

JNF
JNF

Reputation: 3730

Columns are defined by the cells - which are nested in the rows. Also, You would need to run through that more than once (for each row), so you can't spend the variable.

Try the code as following:

<script>
   var c = parseInt(prompt("Enter column ")) // 10
   var r = parseInt(prompt("Enter row ")) // 10
   var cTmp = c;

   while(0<r){
      r--;
      cTmp = c;
      document.write("<tr>")
      while(0<cTmp){
          cTmp--; 
          document.write("<td style></td>")
      }
      document.write("</tr>")
   }
</script>

Edit

You should note that html tables are not defined by rows and columns, rather by rows, and the cells within each row. In essence, this creates columns, but we redefine them for each row.

Upvotes: 0

CJLopez
CJLopez

Reputation: 5815

For starters, you can't treat Javascript like you'd do with PHP. You are risking that the tags are not written at the position you want, but at the start of the document.

I'd recommend you give a read to the "Manipulating DOM" over w3schools

Now, to answer you question, the easiest way to achieve this, is using jquery, that way you don't need to deal with several way to manipulate the DOM and make it crossbrowser

var c = parseInt(prompt("Columns"));
var r = parseInt(prompt("Rows"));

for (var i = 0; i < r; i++) {
    var newRow = $("<tr></tr>");
    for (var j = 0; j < c; j++) {
        newRow.append("<td></td>");
    }
    $("#customTable").append(newRow);
}
table, tr, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table id="customTable" width="100%"></table>

Now, if you need vanilla javascript (i.e. no Jquery)

var c = parseInt(prompt("Columns"));
var r = parseInt(prompt("Rows"));
var table = document.getElementById("customTable");

for (var i = 0; i < r; i++) {
    var newRow = document.createElement("tr");
    for (var j = 0; j < c; j++) {
        var newColumn = document.createElement("td");
        newRow.appendChild(newColumn);
    }
    table.appendChild(newRow);
}
table, tr, td {
    border: 1px solid black;
}
<table id="customTable" width="100%"></table>

Upvotes: 1

Related Questions