Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print calendar vertically using jquery

I was trying to print calendar vertically like this

1  8  15 22 29
2  9  16 23 30
3  10 17 24 31
4  11 18 25 
5  12 19 26
6  13 20 27
7  14 21 28

I tried below code

var x = 1;
var $tbodyTr = $('<tr>').appendTo($tbody);
for(var i = 1; i <= 31; i++){
   if(x == 7) {
       x = 1;
       $tbodyTr = $('<tr>').appendTo($tbody);
   } 
   $tbodyTd = $('<td>',{html: i}).appendTo($tbodyTr);
   x++;
}

But it prints horizontally.

var $table = $('<table>',{'class': 'table-calendar table table-hover text-center table-calendar'});
var $tbody = $('<tbody>').appendTo($table);
var x = 1;
var $tbodyTr = $('<tr>').appendTo($tbody);
for(var i = 1; i <= 31; i++){

	if(x == 7) {
		x = 1;
		$tbodyTr = $('<tr>').appendTo($tbody);
	} 
	$tbodyTd = $('<td>',{html: i}).appendTo($tbodyTr);
	x++;
} 
$('.table-responsive').html($table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">

</div>

Looking for help, want vertical output.

like image 381
Nirav Joshi Avatar asked Sep 25 '26 16:09

Nirav Joshi


1 Answers

To solve this you can build the column values using their ordinal positions.

As this is for a calendar you can assert that a grid of 6*6 cells (or 7*5 in your example) is enough to fit all 31 days in, no matter where the starting position is. As such you can use two loops and calculate the day number based on the current row/col, like this

var $table = $('<table>', {
  'class': 'table-calendar table table-hover text-center table-calendar'
}).appendTo('.table-responsive');
var $tbody = $('<tbody>').appendTo($table);
var rowCount = 7, colCount = 5;

var html = '';
for (var row = 0; row < rowCount; row++) {
  html += '<tr>';
  for (var col = 0; col < colCount; col++) {
    var day = (row + 1) + (col * rowCount);
    if (day < 32) 
      html += `<td>${day}</td>`;
  } 
  html += '</tr>';
}
$tbody.append(html);
td { padding: 5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive"></div>

This logic can then be easily tweaked to move the starting position based on day of week and also the number of days in the given month.

like image 167
Rory McCrossan Avatar answered Sep 27 '26 04:09

Rory McCrossan



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!