Skip to content
Advertisement

I want to create a html table layout in jQuery

I am trying to create an Html table layout using jQuery but I don’t know where I am doing mistakes.

When I try to run this and check the console tab the error comes with undefined( i and table2)

I just want to show the table on the chrome page means I want the output.

$(document).ready(function() {
  function table() {
    this.column = col;
  }

  function col(value1, value2) {
    var multiply = (value1 * value2);
    return multiply;
  }
  var table2 = new table();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
  <thead>
    <tr>
      <script>
        for (var j = 1; j <= 10; j++) {
          console.log("<th><label'>" + i + "</label></th>");
        }
      </script>
    </tr>
  </thead>

  <tbody>
    <script>
      for (var i = 1; i <= 5; i++) {
        console.log("<tr>");
        for (var k = 1; k <= 5; k++) {
          var value1 = i;
          var value2 = k;
          console.log("<td>" + table2.column(value1, value2) + "</td>");
        }
        console.log("</tr>");
      }
    </script>
  </tbody>
</table>

Advertisement

Answer

Simpling adding console.log inside a script tag in you required place will not add the content to the DOM. You have to manipulate the template as string and set it as the html content of the target using html method in jQuery.

Also the loop index used in the for loop was j and you were consoling it with i. The index was looping till 10. But you have only 5 columns inside a row. If that is not purposeful, you have to user loop from 1 to 5

$(document).ready(function () {
  maniputalteHeader();
  function table() {
    this.column = col;
  }

  function col(value1, value2) {
    var multiply = (value1 * value2);
    return multiply;
  }
  var table2 = new table();
  let template = '';
  for (var i = 1; i <= 5; i++) {
    template += "<tr>";
    for (var k = 1; k <= 5; k++) {
      var value1 = i;
      var value2 = k;
      template += "<td>" + table2.column(value1, value2) + "</td>";
    }
    template += "</tr>";
  }
  $("#tbody").html(template);
});

function maniputalteHeader() {
  let template = '';
  for (var j = 1; j <= 5; j++) {
    template += "<th><label'>" + j + "</label></th>";
  }
  $("#thead").html(template);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
  <thead>
    <tr id="thead">
    </tr>
  </thead>

  <tbody id="tbody">
  </tbody>
</table>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement