Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically created table with variable number of rows

I need to make table with number of rows equals to number of days in current month, can anyone help me with that? I need to create that dynamically using jquery or javascript.

like image 709
freshbm Avatar asked Nov 25 '25 14:11

freshbm


2 Answers

You could do something like this:

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}


var $table = $('<table>');
var $tbody = $('<tbody>');

var days=  daysInMonth(new Date().getMonth(), new Date().getYear());

$table.append($tbody);
for (i = 1; i<= days; i++){
    var $tr = $('<tr>');
    var $td = $('<td>');
    $td.text(i);
    $tr.append($td);
    $tbody.append($tr);
};
$('body').append($table);

fiddle here: http://jsfiddle.net/nicolapeluchetti/WG88Y/

This creates a table with a row for each day of the month. i included a td with the current day.

like image 124
Nicola Peluchetti Avatar answered Nov 27 '25 04:11

Nicola Peluchetti


This is the jQuery part of @dknaack 's answer:

var genTable = function () {
  var $table = jQuery("<table />");
  // days is equeal to @dhnaack 's answer
  var days = DateTime.DaysInMonth(DateTime.Now.Date.Year, DateTime.Now.Date.Month);
  jQuery(days).each(function(i,e) {
    var $tr = jQuery("<tr />");
    var $tr = jQuery("<td />")
    $table.append($tr.append($td));
  });
  return $table;
}

Then you could use it like so:

jQuery("body").append(genTable());
like image 42
Christopher Avatar answered Nov 27 '25 02:11

Christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!