javascript, calendar - javascript

I would like to ask if there's anyway I can 'shift' the calender to the right side of the page? Because I realized that it can only be displayed on the left hand side. I do not really know how to 'shift' it to the right hand side... Neither do I know how to put css in to do it.
Here's the code to make the calendar...
<script type="text/javascript">
// SET ARRAYS
var day_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
var month_of_year = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// DECLARE AND INITIALIZE VARIABLES
var Calendar = new Date();
var year = Calendar.getFullYear(); // Returns year
var month = Calendar.getMonth(); // Returns month (0-11)
var today = Calendar.getDate(); // Returns day (1-31)
var weekday = Calendar.getDay(); // Returns day (1-31)
var DAYS_OF_WEEK = 7; // "constant" for number of days in a week
var DAYS_OF_MONTH = 31; // "constant" for number of days in a month
var cal; // Used for printing
Calendar.setDate(1); // Start the calendar day at '1'
Calendar.setMonth(month); // Start the calendar month at now
/* VARIABLES FOR FORMATTING
NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
tags to customize your caledanr's look. */
var TR_start = '<TR>';
var TR_end = '</TR>';
var highlight_start = '<TD WIDTH="10"><TABLE CELLSPACING=0 BORDER=1 BGCOLOR=DEDEFF BORDERCOLOR=CCCCCC><TR><TD WIDTH=5><B><CENTER>';
var highlight_end = '</CENTER></TD></TR></TABLE></B>';
var TD_start = '<TD WIDTH="1"><CENTER>';
var TD_end = '</CENTER></TD>';
/* BEGIN CODE FOR CALENDAR
NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
tags to customize your calendar's look.*/
cal = '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
cal += '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=1>' + TR_start;
cal += '<TD COLSPAN="' + DAYS_OF_WEEK + '" BGCOLOR="#EFEFEF"><CENTER><B>';
cal += month_of_year[month] + ' ' + year + '</B>' + TD_end + TR_end;
cal += TR_start;
// LOOPS FOR EACH DAY OF WEEK
for(index=0; index < DAYS_OF_WEEK; index++)
{
// BOLD TODAY'S DAY OF WEEK
if(weekday == index)
cal += TD_start + '<B>' + day_of_week[index] + '</B>' + TD_end;
// PRINTS DAY
else
cal += TD_start + day_of_week[index] + TD_end;
}
cal += TD_end + TR_end;
cal += TR_start;
// FILL IN BLANK GAPS UNTIL TODAY'S DAY
for(index=0; index < Calendar.getDay(); index++)
cal += TD_start + '' + TD_end;
// LOOPS FOR EACH DAY IN CALENDAR
for(index=0; index < DAYS_OF_MONTH; index++)
{
if( Calendar.getDate() > index )
{
// RETURNS THE NEXT DAY TO PRINT
week_day =Calendar.getDay();
// START NEW ROW FOR FIRST DAY OF WEEK
if(week_day == 0)
cal += TR_start;
if(week_day != DAYS_OF_WEEK)
{
// SET VARIABLE INSIDE LOOP FOR INCREMENTING PURPOSES
var day = Calendar.getDate();
// HIGHLIGHT TODAY'S DATE
if( today==Calendar.getDate() )
cal += highlight_start + day + highlight_end + TD_end;
// PRINTS DAY
else
cal += TD_start + day + TD_end;
}
// END ROW FOR LAST DAY OF WEEK
if(week_day == DAYS_OF_WEEK)
cal += TR_end;
}
// INCREMENTS UNTIL END OF THE MONTH
Calendar.setDate(Calendar.getDate()+1);
}// end for loop
cal += '</TD></TR></TABLE></TABLE>';
// PRINT CALENDAR
document.write(cal);
// End -->
</script>

Add an align=right to the table definition on line 38.
So you'll have:
cal = '<TABLE ALIGN=RIGHT BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
Instead of:
cal = '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';

Related

How to Select an Element of An Appended Table With Jquery

I built a table by using .append on a div (id = calendarData) that is in the html:
$j('#calendarData').append(
'<table class="grid" id="calendar" href="#" style="max-width:1200px"><th colspan="7" align=""center">' +
months[currentMonth] + " " + currentYear + '</div></th><tbody>'+
'<tr><td>Sun</td><td>Mon</td><td>Tues</td><td>Wed</td><td>Thurs</td><td>Fri</td><td>Sat</td>'
);
Then I added all of the cells to the table:
for(var i=0; i<6; i++){
$j('#calendar > tbody:last-child').append(
'</tr><tr>'
);
for(var j=0;j<7;j++){
if(inMonth == 0 && day > getDaysInMonth(startDate.getMonth()-1)){
day = 1;
inMonth = 1;
}
else if(inMonth == 1 && day > getDaysInMonth(startDate.getMonth())){
day = 1;
inMonth == 2;
}
$j('#calendar > tbody:last-child').append(
'<td class="square">' + day + '</td>'
);
day++;
}
}
$j('#calendarData > tbody:last-child').append(
'</tr></tbody></table>'
);
After this I need to go back and select each td and give it a color if that day is active(determined in a later function) but every time I try to grab it the system comes back with undefined.
Everything from:
$j('#calendarData tbody:last-child').style.backgroundColor = 'green';
to
var t = document.getElementById("calendar");
var r = t.getElementsByTagName("tr")[0];
var d = r.getElementsByTagName("td")[0];
d.style.backgroundColor ='green';
Every time it throws an Error 'Cannot change Background Color of Undefined"
Any ideas what I am doing wrong?
Not sure why it's doubling-up the dates in my example, but that's not the point.
To style the injected HTML class after the fact, you can either add the class ahead of time to the CSS, or you can use jQuery .css() to add the styling via jQuery:
setTimeout(function(){
$('.active').css({'color':'maroon','font-weight':'bold','background':'yellow'});
},3000);
$('#calendarData').append('\
<table class="grid" id="calendar" href="#" style="max-width:1200px">\
<th colspan="7" align=""center">' +'June'+ "" + '2016' + '</div></th><tbody>\
<tr><td>Sun</td><td>Mon</td><td>Tues</td><td>Wed</td><td>Thurs</td><td>Fri</td><td>Sat</td></tr>'
);
setTimeout(function(){
//This mimics your generated / injected code
$('#calendarData > table > tbody').append('\
<tr><td class="square">1</td><td class="square">2</td><td class="square">3</td><td class="square">4</td><td class="square">5</td><td class="square">6</td><td class="square">7</td></tr>\
<tr><td class="square">8</td><td class="square">9</td><td class="square">10</td><td class="square active">11</td><td class="square">12</td><td class="square">13</td><td class="square">14</td></tr>\
<tr><td class="square">15</td><td class="square">16</td><td class="square">17</td><td class="square">18</td><td class="square">19</td><td class="square">20</td><td class="square">21</td></tr>\
<tr><td class="square">22</td><td class="square">23</td><td class="square">24</td><td class="square">25</td><td class="square">26</td><td class="square">27</td><td class="square">28</td></tr>\
</tbody></table>'
);
},1500);
.square{text-align:center;}
.active{font-style:italic;font-size:larger;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="calendarData"></div>

Array.sort not working correctly

I need the sort function to sort the dates from the earliest date to the latest date. What can I do to fix this in my tasks table?
var tasks = new Array();
var index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
//add array and populate from tempdate and temptask
//generate html table from 2d javascript array
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a,b){return new Date(b.Date).getTime() - new Date(a.Date).getTime()});
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
I have tried many different syntax variations and can not get the sort function to sort in descending order
Since the date is represented as
the number of milliseconds since 1 January, 1970 UTC (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
the sorting order you are looking for is ascending not descending.
Also, as #birdspider already commented, there is no use of creating new Date objects and invoking the getTime() method. They are comparable as they are.
To summarize the above points, try using the following sorting function:
function sortDatesAsc(tempdateA, tempdateB) {
return tempdateA - tempdateB < 0 ? -1 : (tempdateA > tempdateB ? 1 : 0);
}
tasks.sort(sortDatesAsc);
You're subtracting a.Date from b.Date, exactly the reverse of what you want.
Flip those around (and remove the unnecessary new Date() wrappers, although they're not actually breaking anything) and you'll get the correct sort:
var tasks = [],
index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a, b) {
return a.Date.getTime() - b.Date.getTime()
});
var tablecode = "<table class='tasktable'>" +
"<tr>" +
"<th>Date</th>" +
"<th>Task</th>" +
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode += "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode += "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
document.getElementById('add').addEventListener('click', addTask);
<p>Task:
<input type="text" id="taskinfo" /></p>
<p>Date:
<input type="date" id="taskdate" /></p>
<button id="add">add</button>
<div id="bottomright"></div>

when enter a date in text box start date automatically Show dates of next one year in other textbox endtextbox

I have two textboxes in my asp.net using c# code
HTML Code
<tr>
<td></td>
<td style="text-align: right"><asp:TextBox ID="TxtEndDate" runat="server"
Width="177px" AutoPostBack="True" style="height: 22px"></asp:TextBox>
</td>
<td style="text-align: right">end date</td>
<td style="text-align: right">
<asp:TextBox ID="TextStartDate" runat="server" Width="177px"
AutoPostBack="True" style="height: 22px"></asp:TextBox></td>
<td style="text-align: right; direction: rtl;">
start date
</td>
</tr>
I want that when I enter date in dd/mm/yyyy in first text box (TxtStartDate), it will automatically fill the second text box (TxtEndDate) by adding plus one year in above entered date.
I tried This JavaScript but it is not working
<script type="text/javascript">
$('#TextStartDate').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
var year = myDate.getYear() + 1;
var month = myDate.getYear() + 1;
if (month < 10) {
month = '0' + month;
}
var day = myDate.getDate();
if (day < 10) {
day = '0' + day;
}
$('#TxtEndDate').val(day + '/' + month + '/' + year);
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});
</script>
It's your id's. ASP.NET hijacks your ids and prepends stuff on them. Change all your jquery id calls to
$("[id*=TxtStartDate]")
$("[id*=TxtEndDate]")
So, in your original script, do this:
<script>
$('[id*=TextStartDate]').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
var year = myDate.getYear() + 1;
var month = myDate.getYear() + 1;
if (month < 10) {
month = '0' + month;
}
var day = myDate.getDate();
if (day < 10) {
day = '0' + day;
}
$('[id*=TxtEndDate]').val(day + '/' + month + '/' + year);
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});
</script>
You could solve this with a more simple function:
var dateParts=value.split('/');
$('#TxtEndDate').val(dateParts[0]+'/'+dateParts[1]+'/'+(parseInt(dateParts[2])+1));
To access server controls with javascript you need to do this $('#<%=TextStartDate.ClientId%>') because asp.net controls IDs are generated at runtime.
Also set AutoPostBack to false or else the page will be refreshed every time one of the TextBox lost focus

Parsing to a table in Javascript

I'm trying to create a calander that can later be styled with CSS. Here is the JS and HTML codes. There is a CSS stylesheet as well but its just used for color and positioning. In the Javascript, I would like to build the table based off the first and last days of the month and insert a new row at the end of each week. As is the Javascript does nothing. When you remove the first if statement, it seems to iterate only once. I'm not sure where I'm screwing up in trying to create the table.
function setDate() {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
document.getElementById("myDay").value = day;
document.getElementById("myMonth").value = month;
document.getElementById("myYear").value = year;
}
function buildCalendar() {
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
document.write("<table class='caltable' border='1'><tr><th>");
document.write("<tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th>");
document.write("</th></tr>");
var col = 0;
for (var i = theDate; i < lastDay + 1; i++) {
if (col == 0) {
document.write("<tr><td>" + i "</td>");
}
if (col == 6) {
document.write("<td>" + i + "</td></tr>");
col == 0;
} else {
document.write("<td>" + i + "</td>");
col++;
}
}
document.write("</table>");
}
function getMonthName() {
var e = getElementById("myMonth").selectedIndex;
var monthName = e.options[e.selectedIndex].text;
return monthName;
}
Here is the HTML file. It's basically just a wrapper div with some other divs inside for holding the calendar eventually a scheduler, as well as the current date. Right now I'm simply trying to get the the table (see the javascript) to build. Ideally it would be in the div with the id "bottomLeft".
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "./CSS/calendar.css">
<script type = "text/javascript" src = "./Calendar/calendar.js"></script>
<script type = "text/javascript" src = "./Calendar/task.js"></script>
</head>
<body onLoad = "setDate(); buildCalendar();">
<div id = "wrapper">
<div id = "left"> Left Div </div>
<div id = "right"> Right Div </div>
<div id = "bottomLeft"> Shows calendar </div>
<div id = "topLeft"> Day:<input id = "myDay" type="number" min = "1" max = "31">Month:<select id = "myMonth"><option value = "0">January</option> <option value = "1">February</option><option value = "2">March</option><option value = "3">April</option><option value = "4">May</option><option value = "5">June</option><option value = "6">July<option value = "7">August</option><option value = "8">September</option><option value = "9">October</option><option value = "10">November</option><option value = "11">December</option></select> Year:<input id = "myYear" type = "number" min = "100"> TopLeft Div shows form components for date </div>
<div id = "topRight"> Shows the form to add task </div>
<div id = "bottomRight"> Show list of tasks </div>
</div>
</body>
</html>
In addition to the mistakes Ceesie123456 mentioned, you need to remove the extra <tr><th> from the opening table tag string. As a means of getting the calendar into the bottomLeft div, you can use set the element's innerHTML property. Finally, you're missing a piece of logic which check for when the end of the calendar is not the end of a row, which means the table won't line up correctly. So, an example:
function buildCalendar(){
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
var tableString = ("<table class='caltable' border='1'>");
tableString = tableString + ("<thead><tr><tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th></tr></thead>");
tableString = tableString + "<tbody>";
var col = 0;
for (var i = theDate; i <= lastDay; i++)
{
if(col == 0)
{
tableString = tableString + ("<tr>");
}
tableString = tableString + "<td>" + i + "</td>";
if (col == 6 || i == lastDay)
{
tableString = tableString + ("</tr>");
col = 0;
}
else
{
col++;
}
}
tableString = tableString + ("</tbody></table>");
document.getElementById("bottomLeft").innerHTML = tableString;
}
U made a few mistakes in ur Javascript code.
if (col == 6)
{
document.write("<td>" + i + "</td></tr>");
col == 0; //this should be changed to col = 0; with col = 0; u set col to 0.
}
and
if(col == 0)
{
document.write("<tr><td>" + i "</td>");
}
u should change it to:
if(col == 0)
{
document.write("<tr><td>" + i + "</td>"); // combine string with variable and string.
}

Beginner JavaScript help(functions)

I'm having some trouble copying the scripts and HTML from the calender on refdesk.com. I need put the JavaScript on a different style sheet and use those functions to recreate the calender on a HTML page. Here is what I have so far, any tips will help. This is a homework assignment so I'm not looking for the answers.
JavaScript -
function initialize()
{
buildCal();
updateCalender();
}
var themonths = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
var todaydate = new Date();
var curmonth = todaydate.getMonth() + 1; //get current month (1-12)
var curyear = todaydate.getFullYear(); //get current year
function buildCal(month, year, cM, cH, cDW, cD, border)
{
var mn = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var dim = [31,0,31,30,31,30,31,31,30,31,30,31];
var firstDaySelectedMonth = new Date(year, month - 1, 1); //DD replaced line to fix date bug when current day is 31st
firstDaySelectedMonth.od=firstDaySelectedMonth.getDay() + 1; //DD replaced line to fix date bug when current day is 31st
var todaydate = new Date(); //DD added
var scanfortoday = (year == todaydate.getFullYear() && month == todaydate.getMonth() + 1) ? todaydate.getDate() : 0; //DD added
dim[1] = (((firstDaySelectedMonth.getFullYear() % 100 != 0) && (firstDaySelectedMonth.getFullYear() %4 == 0)) || (firstDaySelectedMonth.getFullYear() % 400 == 0)) ? 29 : 28;
var t = '<div class="' + cM + '"><table class="' + cM + '" cols="7" cellpadding="0" border="' + brdr + '" cellspacing="0"><tr align="center">';
t += '<td colspan="7" align="center" class="' + cH + '">' + mn[month - 1] + ' - ' + year + '</td></tr><tr align="center">';
for (s = 0; s < 7; s++)
{
t += '<td class="' + cDW + '">' + "SMTWTFS".substr(s,1) + '</td>';
t += '</tr><tr align="center">';
}
for(i = 1;i <= 42; i++)
{
var x = ((i-firstDaySelectedMonth.od >= 0) && (i-firstDaySelectedMonth.od < dim[month -1 ])) ? i-firstDaySelectedMonth.od + 1 : ' ';
if (x == scanfortoday) //DD added
{
x = '<span id="today">' + x + '</span>'; //DD added
t += '<td class="' + cD + '">' + x +'</td>';
}
if(((i) % 7 == 0) && (i < 36))
{
t += '</tr><tr align="center">';
}
}
return t += '</tr></table></div>';
}
// update calender function
function updateCalendar(theSelection)
{
var themonth = parseInt(theSelection[theSelection.selectedIndex].value) + 1;
var calendarstr = buildCal(themonth, curyear, "main", "month", "daysofweek", "days", 0);
if (document.getElementById)
{
document.getElementById("calendarspace").innerHTML = calendarstr;
}
document.write('<option value="'+(curmonth - 1) + '" selected="yes">Current Month</option>');
for (i = 0; i < 12; i++) //display option for 12 months of the year
{
document.write('<option value="' + i + '">' + themonths[i] + ' ' + curyear + '</option>');
}
}
HTML -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="refdesk.css">
<script src="refdesk.js"></script>
</head>
<body onload="initialize()">
<!-- CALENDAR START -->
<form>
<div id="choicespace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
<select onchange="updatecalendar(this.options)">
<script>
updatecalendar(theselection);
</script>
<option value="1" selected="yes">Current Month</option><option value="0">January 2013</option><option value="1">February 2013</option><option value="2">March 2013</option><option value="3">April 2013</option><option value="4">May 2013</option><option value="5">June 2013</option><option value="6">July 2013</option><option value="7">August 2013</option><option value="8">September 2013</option><option value="9">October 2013</option><option value="10">November 2013</option><option value="11">December 2013</option>
</select>
</div>
<div id="calendarspace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
</div>
</form>
</body>
</html>
First, try to figure how your javascript code really work. Take a look on calendar in javascript as a simple example.
Personally I would indent more to keep things organized. Another thing I would do is just make shorter variables because sometimes i find myself coding wrong because of my huge variable names.

Categories

Resources