admin管理员组

文章数量:1390410

I had html table with 31 rows and 4 table columns I am trying to write javascript(Jquery) to bind first column with dates of the current month.

This is my code

<html xmlns="">
<head>
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.8.0.js"></script>
        <script type="text/javascript">
            $(document).ready(function ($) {
                var table = document.getElementById("myTable")
                var myDate = new Date();
                myDate.setDate(myDate.getDate() - 1)
                for (var i = 0; i < 16; i++) {
                    var row = document.createElement("tr");
                    var cell = document.createElement("td");
                    cell.innerText = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getYear();
                    myDate.setDate(myDate.getDate() + 1)
                    row.appendChild(cell);
                    table.tBodies[0].appendChild(row);
                }
            });
    </script>
</head>

<body>
<table id="myTable"></table>

</body>
</html>

I had html table with 31 rows and 4 table columns I am trying to write javascript(Jquery) to bind first column with dates of the current month.

This is my code

<html xmlns="http://www.w3/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.8.0.js"></script>
        <script type="text/javascript">
            $(document).ready(function ($) {
                var table = document.getElementById("myTable")
                var myDate = new Date();
                myDate.setDate(myDate.getDate() - 1)
                for (var i = 0; i < 16; i++) {
                    var row = document.createElement("tr");
                    var cell = document.createElement("td");
                    cell.innerText = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getYear();
                    myDate.setDate(myDate.getDate() + 1)
                    row.appendChild(cell);
                    table.tBodies[0].appendChild(row);
                }
            });
    </script>
</head>

<body>
<table id="myTable"></table>

</body>
</html>
Share Improve this question edited Mar 8, 2013 at 6:38 asked Sep 4, 2012 at 17:56 user474901user474901 8
  • 13 What is your question? – Jasper de Vries Commented Sep 4, 2012 at 17:57
  • plz describe more with code what you want to do and where you face problem. – Anant Dabhi Commented Sep 4, 2012 at 18:01
  • 2 how can there be a 500 bounty by a questioner who has less than that in points? – abbood Commented Mar 3, 2013 at 14:07
  • 2 @abbood He can give out a 500 bounty with 638 rep. – Antony Commented Mar 3, 2013 at 14:09
  • 3 I am not sure if I understand the question, but I've created the JSFiddle for those who do understand. jsfiddle/nLQ7q – strah Commented Mar 4, 2013 at 14:39
 |  Show 3 more ments

9 Answers 9

Reset to default 4

Here's a solution that also breaks the loop in case we're dealing with a shorter month (e.g. in April, the table will not display 31/4/2013):

$(function() {
    var table = document.getElementById("myTable")
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var firstOfMonth = new Date();
    firstOfMonth.setDate(1);
    for (var i = 0; i < 31; i++) {
        myDate.setDate(firstOfMonth.getDate() + i);
        if (myDate.getMonth() + 1 != month) break;
        var row = document.createElement("tr");
        var cell = document.createElement("td");
        cell.innerText = formatDate(myDate, dateFormat);
        row.appendChild(cell);
        table.tBodies[0].appendChild(row);
    }
});

Link to jsfiddle

Note: the OP mentions javascript as the 1st option (jQuery only in backets), that's why I left the code in plain js (with the exception of the DOM ready wrapper). In case that you want a solution that fully independent of jQuery, bind the DOM content load event as described in this SO post

I suppose that your question is related to this question.
In other words, you are looking for a Javascript function that should add to an empty table one row for each day of the current month; each row should have four columns named "Date", "Start Time", "End Time" and "Hour Type" and the first column ("Date") should contain a text input with a date in the format "dd/mm/yyyy".
If so, here is my solution:

<!DOCTYPE html>
<html>
    <head>
        <script language="javascript" type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
        // See https://stackoverflow./questions/4881938/javascript-calculate-number-of-days-in-month-for-a-given-year
        Date.prototype.daysInMonth = function(year, month) { 
            var monthStart  = new Date(year, month, 1);
            var monthEnd    = new Date(year, month + 1, 1);
            var monthLength = Math.round((monthEnd - monthStart) / (1000 * 60 * 60 * 24));
            var mm  = ((month + 1) < 10) ? ('0' + (month + 1)) : (month + 1);
            var ret = new Array();
            for (var i = 1; i <= monthLength; i++) {
                var dd = (i < 10) ? ('0' + i) : i;
                ret.push(dd + '/' + mm + '/' + year);
            }
            return ret;
        };

        function addRows(table, dates) {
            var idx = 1;
            for (var i in dates) {
                table.append('<tr>'+
                             '<td><input name="date'+idx+'" id="date'+idx+'" class="date" value="'+dates[i]+'"></td>'+
                             '<td><input name="startTime'+idx+'" id="startTime'+idx+'"></td>'+
                             '<td><input name="endTime'+idx+'" id="EndTime'+idx+'"></td>'+
                             '<td>'+
                             '<select name="hourType'+idx+'" id="hourType'+idx+'">'+
                             '<option value="">Please select</option>'+
                             '<option value="1">Regular</option>'+
                             '<option value="2">Overtime</option>'+
                             '</select>'+
                             '</td>'+
                             '</tr>');
                idx++;
            }
        }

        $(function() {
            var myDate = new Date();
            var year   = myDate.getFullYear();
            var month  = myDate.getMonth(); 
            var dates  = myDate.daysInMonth(year, month);
            var table  = $("#myTable").find("tbody");
            addRows(table, dates);
        });
        </script>       
    </head>
    <body>
        <form>
          <table id="myTable">
            <thead>
              <tr>
                <th>Date</th>
                <th>Start Time</th>
                <th>End Time</th>
                <th>Hour Type</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </form>
    </body>
</html>

Obviously, the table may also have less than 31 rows, depending on the number of days of the current month.

You are trying to append to the tbody but you didn't defined one. Change HTML to

<table id="myTable"><tbody></tbody></table>

And if you already have rows and cells, you want just to prepend the new cells

for (var i = 0; i < 16; i++) {
                    var cell = document.createElement("td");
                    cell.innerText = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getFullYear();
                    myDate.setDate(myDate.getDate() + 1)
                    $(table).find('tr').eq(i).prepend(cell);
                }

Try this out :- http://jsfiddle/adiioo7/9fQxq/

Use

table.appendChild(row);

instead of

table.tBodies[0].appendChild(row);

Here is a working jsFiddle.

The way I would use :

var d = new Date();              // get current date
var currentMonth = d.getMonth(); // save current month
d.setDate(1);                    // set date to first day of current month

// (...) create your table header

// create 31 rows
for(var i=1; i<=31; i++) {
    var line = $(document.createElement('tr'));
    if(d.getMonth() == currentMonth) {
        // add the date to the first column
        line.append('<td>'+dateToDMY(d)+'</td>')
            .append('<td></td>')
            .append('<td></td>')
            .append('<td></td>');
    } else {
        // in case you always want to have 31 rows, whatever the month
        line.append('<td colspan="4" class="empty">&nbsp</td>');
    }

    $('#myTable').append(line);  // append the line to the table
    d.setDate(d.getDate() + 1);  // increase the date
}

/* 
 * Format Date : dd/mm/yyyy
 * Based on Adrian Maire work
 * http://stackoverflow./a/10685571/1238019
*/
function dateToDMY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '/' + (m<=9 ? '0' + m : m) + '/' + y;
}

Note that using setDate function will automaticaly update the date month with an out of range day (then you don't have to care about leap years)

If I understood your question correctly than you want to bind the first column with dates in current month? Fiddle

$(document).ready(function () {
    // Get today date
    var d = new Date();
    //Get Days of Month
    var n = new Date(d.getYear(), d.getMonth()+1, 0).getDate();

    //Run loop for number of days
    for (var i = 1; i <= n; i++) {
        //Create row data
        var row = '<tr><td>'+ i + "/" + (d.getMonth() + 1) + "/" + d.getFullYear()+'</td><td><td/><td><td/><td><td/></tr>';

        // Append row data to table
        $('#myTable').append(row);
    }
});

You question is not very clear.. but From your code what I understood is that you are creating table 16 rows in which column 1 has date from (CURRENT_DATE - 1) to (CURRENT_DATE+14).

I used template to render table rows. Update the templates as you like to render other columns.

DEMO: http://jsfiddle/nLQ7q/3/

$(document).ready(function ($) {
     var table = $("#myTable")
     var myDate = new Date();
     myDate.setDate(myDate.getDate() - 1);

     var rowTmpl = '<tr><td>{DATE}</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
     var rows = [];

     for (var i = 0; i < 16; i++) {
         var row = rowTmpl.replace('{DATE}', myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getYear());
         myDate.setDate(myDate.getDate() + 1)
         rows.push(row);         
     }

      table.html(rows.join(''));
 });

A little bit fancy version here with a date picker http://jsfiddle/nLQ7q/4/

You can tryout this: FIDDLE

<table id="myTable"></table>

Mind it, you don't have tbody in your markup, so i put that and used the below jquery

-JQUERY-:

  jQuery(document).ready(function ($) {
     var table = $("#myTable");
     var myDate = new Date();
     myDate.setDate(myDate.getDate() - 1)
     for (var i = 0; i < 16; i++) {
        var row = $("<tr>");
        var cell = $("<td>");
        myDate.setDate(myDate.getDate() + 1)
        cell.text(myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getFullYear());
        row.append(cell);
        table.find('tbody').append(row);
    }
    $('#myTable').find('tr').each(function (i, v) {
       $(this).append('<td/><td/><td/>');
       $('td:not(:first)', this).text(i + 1);
    });
 });

At each row in the tr filled first td with dates and created other tds with some default text.

I have eup with this : FIDDLE

 $(function ($) {
     var table = $("#myTable")
     var myDate = new Date();

     myDate.setDate(myDate.getDate() - 1);

     for (var i = 0; i < 16; i++)
     {
         var row = $('<tr/>');         
         var cell = $('<td/>');

         cell.text
          (myDate.getDate() +
           "/" +
           (myDate.getMonth() + 1) +
           "/" +
           (1900 + myDate.getYear()));

         myDate.setDate(myDate.getDate() + 1);

         row.append(cell);
         table.append(row);
     }
 });

本文标签: jqueryBind datetime javascript to table columnStack Overflow