Go to GoReading for breaking news, videos, and the latest top stories in world news, business, politics, health and pop culture.

How to Create Dynamic Tables in JavaScript

104 14
    • 1). Create an array. In a script block, we will use the names of months to create an array (an ordered collection of data in the format [ var myArray = new Array();]) to generate a calendar as the example script below shows:

      var months = new Array();
      months[0] = "January"; months [1] = "February"'
      months[2] = "March"; months[3] = "April";
      months[4] = "May"; months[5] = "June";
      months[6] = "July"; months[7] = "August";
      months[8] = "September"; months[9] = "October";
      months[10] = "November"; months[11] = "December";

    • 2). Create a "new Date" object and store it in the variable "currentDate" (See code in Step 3 below).

    • 3). Create a "currentMonth" variable. The format for the above code is:

      Var currentDate = new Date();
      Var currentMonth = currentDate.getMonth();
      currentDate.setDate(1);

    • 4). Output the table top, first row and the second row. These contain the day of the month and the days of the week as follows:

      Document.write ("<table border=1 callpadding=3
      Cellspacing=0>");
      Document.write(<tr>");
      Document.write("td colspan=7 aligh='center'>"
      Months[currentMonth] + "<td>");
      Document.write ("<tr>");
      Document.write("<td align='center'>S</td>");
      Document.write("<td align='center'>M</td>");
      Document.write("<td align='center'>T</td>");
      Document.write("<td align='center'>W</td>");
      Document.write("<td align='center'>T</td>");
      Document.write("<td align='center'>F</td>");
      Document.write("<td align='center'>S</td>");
      Document.write("</tr>");

    • 5). Handle the first day of the month case. This is where the first day of the month is not a Sunday and the code format is:

      If (currentDate.getDay() !=0){
      Document.write("<tr>");
      For (i=0; i<currentDate.getDay(); i++) {
      Document.write ("<td> <td>");
      }
      }

    • 6). Create a "while" loop. Inside the loop do a couple of checks to determine where the tags will fall as follows:

      While (currentDate.getMonth() ==currentMonth){
      If (currentDate.getDay ==0) {
      Document.write ("<tr>");
      }
      document.write ("<td align='center'>" +
      currentDate.getDate() + "</td>");
      if (currentDate.getDate() ==6){
      document.write("</tr>");
      }
      currentDate.setDate(currentDate.getDate() + 1)'
      )

    • 7). Use a "for" loop to complete last rows as follows:

      For (I = currentDate.getDate(); i<= 6; i++) {
      Document.write("<td> <td>");

    • 8). Close the table tag. Output a closing table tag as follows:

      Document.write("</table>");

Source...

Leave A Reply

Your email address will not be published.