karansys
karansys

Reputation: 2719

Create table of specified column and rows in Jquery

I am new to jQuery, I want to create table with specific number of rows and columns in jQuery.

Here is what I tried this creates table with specific number of rows but it doesn't create table of specific number of columns

function constructTable () {
  let table = $('<table>').first().prepend('<caption><b> Borrow </b></caption>');
  let row;
  let cell1;
  let cell2;
  table.attr({"id":"burrow"});

  for(i=0; i < 3; i++) {
    row = $('<tr>');
    table.append(row);
   
  }
  
   for ( i = 0 ; i < 4; i++ ) {
    cell1 = $('<td>').text('cell ' + i);
    row.append(cell1);
  }

  
    $("#borrowLicensediv").append(table);
    document.getElementById('borrowLicensediv').style.display = '';	
}
<!doctype html>
<html>
<head>
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    
  
</head>
<body onload="constructTable ()" style="background: white;">
    <div id="borrowLicensediv" style="display: none; margin-top:10px; margin-bottom:25px; margin-left:20px; margin-right:37px;"></div>
    
</body>
</html>

Upvotes: 0

Views: 443

Answers (2)

geco17
geco17

Reputation: 5294

Before you append rows to the table these must first have cells otherwise you're going to have empty rows in your table with no columns. Leaving jQuery aside for a moment, the general problem is:

  1. Build a row
  2. Append it to the table
  3. Repeat 1 and 2 for all rows to add

Step (1) implies that you first create the cells you want in the row and add them to the row. This means you're going to have nested loops (whereas in your example they're inline).

You need something more like

for(i=0; i < 3; i++) {
    var row = "<tr>";
    for ( j = 0 ; j < 4; j++ ) {
        var value = "cell " + i + "," + j;
        var td = "<td>" + value + "</td>";
        row += td;
    }
    row += "</tr>";
    table.append(row);
}

Upvotes: 1

Nawed Khan
Nawed Khan

Reputation: 4401

You are adding the TDs to the last Row because your cell loop is outside of the Row loop. We need to move the loop inside and fix the iterator variable, like this:

for(var r=0; r < 3; r++) {
   row = $('<tr>');

   for ( var c = 0 ; c < 4; c++ ) {
      cell = $('<td>').text('cell ' + r+c);
      row.append(cell);
   }
   table.append(row);   
}

Upvotes: 1

Related Questions