How can I auto-generate years in a calendar? - javascript

So, I'm doing a project which includes having a calendar on it.
So I downloaded a template and I customized it.
The problem is, the calendar only has the year "2017" implemented.
My question is, can I auto-generate the following years?
And if I can, how?
Downhere I'm showing you my code (html and Js)
index.html:
<script>
// fill the month table with column headings
function day_title(day_name) {
document.write("<div class='c-cal__col'>" + day_name + "</div>");
}
// fills the month table with numbers
function fill_table(month, month_length, indexMonth) {
day = 1;
// begin the new month table
document.write("<div class='c-main c-main-" + indexMonth + "'>");
//document.write("<b>"+month+" "+year+"</b>")
// column headings
document.write("<div class='c-cal__row'>");
day_title("Dom");
day_title("Seg");
day_title("Ter");
day_title("Qua");
day_title("Qui");
day_title("Sex");
day_title("Sab");
document.write("</div>");
// pad cells before first day of month
document.write("<div class='c-cal__row'>");
for (var i = 1; i < start_day; i++) {
if (start_day > 7) {
} else {
document.write("<div class='c-cal__cel'></div>");
}
}
// fill the first week of days
for (var i = start_day; i < 8; i++) {
document.write(
"<div data-day='2019-" +
indexMonth +
"-0" +
day +
"'class='c-cal__cel'><p>" +
day +
"</p></div>"
);
day++;
}
document.write("</div>");
// fill the remaining weeks
while (day <= month_length) {
document.write("<div class='c-cal__row'>");
for (var i = 1; i <= 7 && day <= month_length; i++) {
if (day >= 1 && day <= 9) {
document.write(
"<div data-day='2019-" +
indexMonth +
"-0" +
day +
"'class='c-cal__cel'><p>" +
day +
"</p></div>"
);
day++;
} else {
document.write(
"<div data-day='2017-" +
indexMonth +
"-" +
day +
"' class='c-cal__cel'><p>" +
day +
"</p></div>"
);
day++;
}
}
document.write("</div>");
// the first day of the next month
start_day = i;
}
document.write("</div>");
}
</script>
<br>
<header>
<div class="wrapper">
<div class="c-monthyear">
<div class="c-month">
<span id="prev" class="prev fa fa-angle-left" aria-hidden="true"></span>
<div id="c-paginator">
<span class="c-paginator__month">JANEIRO</span>
<span class="c-paginator__month">FEVEREIRO</span>
<span class="c-paginator__month">MARÇO</span>
<span class="c-paginator__month">ABRIL</span>
<span class="c-paginator__month">MAIO</span>
<span class="c-paginator__month">JUNHO</span>
<span class="c-paginator__month">JULHO</span>
<span class="c-paginator__month">AGOSTO</span>
<span class="c-paginator__month">SETEMBRO</span>
<span class="c-paginator__month">OUTUBRO</span>
<span class="c-paginator__month">NOVEMBRO</span>
<span class="c-paginator__month">DEZEMBRO</span>
</div>
<span id="next" class="next fa fa-angle-right" aria-hidden="true"></span>
</div>
<span class="c-paginator__year">2019</span>
</div>
</div>
</header>
<div class="c-calendar">
<div class="c-calendar__style c-aside">
<a class=" o-btn " >Anular Senha </a>
<div class="c-aside__day">
<span class="c-aside__num"></span> <span class="c-aside__month"></span>
</div>
</div>
<div class="c-cal__container c-calendar__style">
<script>
// CAHNGE the below variable to the CURRENT YEAR
year = 2017;
// first day of the week of the new year
today = new Date("Janeiro 1, " + year);
start_day = today.getDay() + 1;
fill_table("Janeiro", 31, "01");
fill_table("Fevereiro", 28, "02");
fill_table("Março", 31, "03");
fill_table("Abril", 30, "04");
fill_table("Maio", 31, "05");
fill_table("Junho", 30, "06");
fill_table("Julho", 31, "07");
fill_table("Agosto", 31, "08");
fill_table("Setembro", 30, "09");
fill_table("Outubro", 31, "10");
fill_table("Novembro", 30, "11");
fill_table("Dezembro", 31, "12");
</script>
index.js:
//global variables
var monthEl = $(".c-main");
var dataCel = $(".c-cal__cel");
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var monthText = [
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro"
];
var indexMonth = month;
var todayBtn = $(".c-today__btn");
var addBtn = $(".js-event__add");
var saveBtn = $(".js-event__save");
var closeBtn = $(".js-event__close");
var winCreator = $(".js-event__creator");
var inputDate = $(this).data();
today = year + "-" + month + "-" + day;

If you're looking for a quick solution you don't need to code yourself, you could use something like https://fullcalendar.io/.

You can manually create an Array of years based on the current year and the number of years you want in your template.
The following code should cover the basics for what you need, change variables depending on your requirements.
let currentYear = new Date().getUTCFullYear();
let startYear = 2016;
let endYearIncrement = 3;
let years = [];
for (let i = 0; i <= currentYear - startYear + endYearIncrement; i++) years.push(startYear + i);
The example should generate an array with the following values.
[2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023]
You could also generate the same array using Javascript's Array built-in function Array.from().
let years = Array.from( {length: currentYear - startYear + endYearIncrement + 1}, (v, i) => i + startYear )
Again, you can update the code so that you cover the years that you need.

Related

Showing days left from a date entry?

So if I have <ons-input style="padding-bottom: 15px;" type="date" id="expiration" required="required"></ons-input>, would it be possible to take the date entered and display the days left until that date is reached and count down each day? exp: if todays 2020-12-4 and I input a new date 2020-12-6, then you have 2 days left, then tomorrow it would display 1 day left.
HTML:
<template id="mylist.html">
<ons-page id='mylist'>
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="fn.open()">
<ons-icon icon="md-menu"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center">
My List
</div>
</ons-toolbar>
<div style="padding-top: 15px; text-align: center;">
<ons-input type="text" class="select-input--underbar" id="food" placeholder="Enter item here . . ."></ons-input>
<br></br>
<label for="expiration">Expiration Date:</label>
<ons-input style="padding-bottom: 15px;" type="text" id="expiration" placeholder = "YYYY-MM-DD" value = ""></ons-input>
<ons-button class="btnAdd" id="start-count" modifier="large" onclick="addItem()">Add Item</ons-button>
</div>
<ons-list id='foodList'>
<ons-list-header>Listed Items:</ons-list-header>
<div class="countdown-content">
<ons-list-item>
<span id="day"></span> Days
<span id="hour"></span> Hours
<span id="minute"></span> Minutes
<span id="second"></span> Seconds
</ons-list-item>
</div>
</ons-list>
</ons-page>
</template>
JavaScript:
function listItems(tx, rs)
{
var output = '';
var foodList = document.getElementById('foodList');
for(i = 0; i < rs.rows.length; i++)
{
var row = rs.rows.item(i);
output += "<ons-list-item>" + "Item: " + row.food + " " + "<br></br>" + "Expiration: " + row.expiration + "<br></br>" + "Days: " + day + "<br></br>" + "Hours: " + hour + "<br></br>" + "Minutes: " + minute + "<br></br>" + "Seconds: " + second +
"<div class=\"right\"> <ons-button onclick='deleteItems(" + row.ID + ");') ><ons-icon icon=\"trash\"></ons-icon></ons-button></div>" +
"</ons-list-item>";
}
foodList.innerHTML = output;
}
function addItem()
{
var foodText = document.getElementById("food");
var expText = document.getElementById("expiration");
var foodVal = foodText.value;
var expVal = expText.value;
db.transaction(function(tx)
{
tx.executeSql("INSERT INTO foodLogs (food, expiration) VALUES (?, ?)", [foodVal, expVal])
});
foodText.value = "";
expText.value = "";
fn.load("mylist.html");
}
function deleteItems(id)
{
db.transaction(function(tx)
{
tx.executeSql("DELETE FROM foodLogs WHERE ID=?", [id], gotSuccess, gotError);
});
}
var timer = null;
var end;
var toZero;
var btn = document.getElementById("btnAdd");
var oDay = document.getElementById("day");
var oHour = document.getElementById("hour");
var oMinute = document.getElementById("minute");
var oSecond = document.getElementById("second");
var endtime = document.getElementById("expiration");
var startBtn = document.getElementById("start-count");
toZero = oDay.innerHTML = oHour.innerHTML = oMinute.innerHTML = oSecond.innerHTML = "00";
startBtn.onclick = function() {
end = endtime.value;
if (!end) {
alert("Please enter date!")
return false;
};
countDown(tx, rs);
timer = setInterval(countDown, 1000);
}
function countDown(tx, rs) {
var timedate = new Date(Date.parse(end.replace(/-/g, "/")));
var now = new Date();
var date = (timedate.getTime() - now.getTime()) / 1000;
var day = Math.floor(date / (60 * 60 * 24));
var _hour = date - day * 60 * 60 * 24;
var hour = Math.floor(_hour / (60 * 60));
var _minute = _hour - hour * 60 * 60;
var minute = Math.floor(_minute / (60));
var _second = _minute - minute * 60;
var second = Math.floor(_second);
}
function toDou(n) {
if (n < 10) {
return '0' + n;
} else {
return '' + n;
}
}
if (date > 0) {
oDay.innerHTML = toDou(day);
oHour.innerHTML = toDou(hour);
oMinute.innerHTML = toDou(minute);
oSecond.innerHTML = toDou(second);
} else {
btn.className = "";
btn.className = "btn";
btn.onclick = function() {
alert("oops")
}
endtime.value = "";
clearInterval(timer);
toZero;
}
Edit: Current error is "Uncaught TypeError: Cannot set property 'innerHTML' of null" at line 106 which is toZero = oDay.innerHTML = oHour.innerHTML = oMinute.innerHTML = oSecond.innerHTML = "00";, haven't gotten any time output yet. It is instead giving undefined.
Edit: For the days, hours, minutes, and seconds I am receiving [object HTMLSpanElement] instead of the actual values behind the elements when viewing the page? Overall, the value isn't being read correctly.
Code Example: https://codepen.io/Wssoop/pen/poEbzve

Astra theme disabling javascript links

I have a working calendar demo. I have tested the code on more than one theme and everything works perfectly. The code however won't work with Astra Theme which is what I am using for my WordPress Website. I am not sure what the problem is at this point maybe someone would help me with this. This code also adds links to the dates. The problem is that Astra Theme strips the dates of the links when you change the date using the navigation buttons or date/month selector. Other themes seem to work perfectly. I checked console for errors and this is what I see:
(index):267 Uncaught TypeError: links is not a function
at previous ((index):267)
at HTMLButtonElement.onclick ((index):182)
The code is
<div class="wrapper">
<div class="container-calendar">
<h3 id="monthAndYear"></h3>
<div class="button-container-calendar">
<button id="previous" onclick="previous()">‹</button>
<button id="next" onclick="next()">›</button>
</div>
<table class="table-calendar" id="calendar" data-lang="en">
<thead id="thead-month"></thead>
<tbody id="calendar-body"></tbody>
</table>
<div class="footer-container-calendar">
<label for="month">Jump To: </label>
<select id="month" onchange="jump()">
<option value=0>Jan</option>
<option value=1>Feb</option>
<option value=2>Mar</option>
<option value=3>Apr</option>
<option value=4>May</option>
<option value=5>Jun</option>
<option value=6>Jul</option>
<option value=7>Aug</option>
<option value=8>Sep</option>
<option value=9>Oct</option>
<option value=10>Nov</option>
<option value=11>Dec</option>
</select>
<select id="year" onchange="jump()"></select>
</div>
</div>
</div>
<script>
function generate_year_range(start, end) {
var years = "";
for (var year = start; year <= end; year++) {
years += "<option value='" + year + "'>" + year + "</option>";
}
return years;
}
var today = new Date();
var currentMonth = today.getMonth();
var currentYear = today.getFullYear();
var selectYear = document.getElementById("year");
var selectMonth = document.getElementById("month");
var createYear = generate_year_range(2016, 2021);
/** or
* createYear = generate_year_range( 1970, currentYear );
*/
document.getElementById("year").innerHTML = createYear;
var calendar = document.getElementById("calendar");
var lang = calendar.getAttribute('data-lang');
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayHeader = "<tr>";
for (day in days) {
dayHeader += "<th data-days='" + days[day] + "'>" + days[day] + "</th>";
}
dayHeader += "</tr>";
document.getElementById("thead-month").innerHTML = dayHeader;
monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);
function next() {
currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
links ()
}
function previous() {
currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
showCalendar(currentMonth, currentYear);
links ()
}
function jump() {
currentYear = parseInt(selectYear.value);
currentMonth = parseInt(selectMonth.value);
showCalendar(currentMonth, currentYear);
links ()
}
function showCalendar(month, year) {
var firstDay = (new Date(year, month)).getDay();
tbl = document.getElementById("calendar-body");
tbl.innerHTML = "";
monthAndYear.innerHTML = months[month] + " " + year;
selectYear.value = year;
selectMonth.value = month;
// creating all cells
var date = 1;
for (var i = 0; i < 6; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
cell = document.createElement("td");
cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > daysInMonth(month, year)) {
break;
} else {
cell = document.createElement("td");
cell.setAttribute("data-date", date);
cell.setAttribute("data-month", month + 1);
cell.setAttribute("data-year", year);
cell.setAttribute("data-month_name", months[month]);
cell.className = "date-picker";
cell.innerHTML = "<span>" + date + "</span>";
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
cell.className = "date-picker selected";
}
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row);
}
}
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
function links () {
document.querySelectorAll('td.date-picker > span').forEach(element => {
var year = element.parentElement.getAttribute('data-year');
var month = element.parentElement.getAttribute('data-month');
var day = element.textContent;
if (month.length === 1) {
month = "0" + month;
}
if (day.length === 1) {
day = "0" + day;
}
element.innerHTML = '' + element.textContent + ' '
})
}
links ()
</script>

Problems with Datetime Periods In es-AR browser

i have a problem with datetime using javascript in es-AR browser.
It is a select that changes period every 15 days or so.
The problem is when I want to spend a date in a browser in Argentine Spanish, given that the format of:
M / d / yyyy to d / M / yyyy then it breaks my date.
I already tried an "If (es-AR)" but it is not the best solution for me. I would like to have a good answer about some feasible solution.
Here I leave the code thank you very much.
function InitializeDropdownlistOfFirstOption(dropdownName, step) {
$('#fromPeriodValidation').hide();
$('#toPeriodValidation').hide();
var dropdownList = $('#' + dropdownName);
var timeperiod = dropdownList.val();
var reg = new RegExp("\\.|-", "g");
var userLang = navigator.language || navigator.userLanguage;
if (String(userLang) == 'es-AR') {
alert(String(cultureInfo));
var formattimeperiod = timeperiod.replace(reg, "/");
if (formattimeperiod.split("/")[0] > 12) {
var tempDay = formattimeperiod.split("/")[0];
var tempMonth = formattimeperiod.split("/")[1];
var tempYear = formattimeperiod.split("/")[2];
formattimeperiod = tempMonth + "/" + tempDay + "/" + tempYear;
}
timeperiod = formattimeperiod;
}
var timeperioddate = new Date(timeperiod);
var month = timeperioddate.getMonth();
var day = timeperioddate.getDate();
var year = timeperioddate.getFullYear();
var option;
dropdownList.get(0).remove(0);
if (day <= 15) {
switch (step) {
case 1:
day = new Date(new Date(year, (month + 1) % 12, 1).getTime() - 1000 * 60 * 60 * 24).getDate();
option = new Date(year, month, day).format(pattern);
dropdownList.prepend("<option value='" + option + "'>" + option + "</option>");
break;
case -1:
month--;
if (month < 1) {
month += 12;
year--;
}
if (month == 12) {
day = 31;
} else {
day = new Date(new Date(year, (month + 1) % 12, 1).getTime() - 1000 * 60 * 60 * 24).getDate();
}
option = new Date(year, month, day).format(pattern);
dropdownList.prepend("<option value='" + option + "'>" + option + "</option>");
break;
}
} else {
switch (step) {
case 1:
month++;
if (month > 12) {
month = 1;
year++;
}
if (month == 12) {
day = 31;
} else {
day = new Date(new Date(year, (month) % 12, 1).getTime() - 1000 * 60 * 60 * 24).getDate();
}
option = new Date(year, month, 15).format(pattern);
dropdownList.prepend("<option value='" + option + "'>" + option + "</option>");
break;
case -1:
option = new Date(year, month, 15).format(pattern);
dropdownList.prepend("<option value='" + option + "'>" + option + "</option>");
break;
}
}
dropdownList.get(0).selectedIndex = 0;
}
<div class="timeperiod" id="timeperiod">
<div style="width: 40%;float: left">
<label class="lblTime"><b>From Time Period</b></label>
<form class="form">
<button type="button" class="btn btn-primary button" onclick="InitializeDropdownlistOfFirstOption('drpfromdatePeriod', -1)">< </button>
<select name="drpfromdatePeriod" class="drpdateperiod" id="drpfromdatePeriod" onchange="SelectPeriod('drpfromdatePeriod')"></select>
<button type="button" class="btn btn-primary button" onclick="InitializeDropdownlistOfFirstOption('drpfromdatePeriod', 1)">> </button>
<img src="#Url.ImportContent("~/Content/images/time_period_calendar.png")" class="imgCalendar" id="imgFromdate" />
</form>
<label class="lblTime"><b>To Time Period</b></label>
<form class="form">
<button type="button" class="btn btn-primary button" onclick="InitializeDropdownlistOfFirstOption('drptodatePeriod', -1)">< </button>
<select name="drptodatePeriod" class="drpdateperiod" id="drptodatePeriod" onchange="SelectPeriod('drptodatePeriod')"></select>
<button type="button" class="btn btn-primary button" onclick="InitializeDropdownlistOfFirstOption('drptodatePeriod', 1)">> </button>
<img src="#Url.ImportContent("~/Content/images/time_period_calendar.png")" class="imgCalendar" id="imgTodate" />
</form>
</div>
<div>
<input type="checkbox" id="cbVat" value="Only return expense receipts with VAT" onclick="SelectVat(this.checked)"/>
<label class="lblTime" id="lbVatMessage"> <b>Only return expense receipts with VAT</b></label>
<img src="#Url.ImportContent("~/Content/images/info.gif")" class="imgInfo" title="If this checkbox is selected, the application will only return receipts for expenses with VAT." />
</div>
</div>
I appreciate any help :D
enter image description hereenter image description here
Trying to globally solve the time format problem by yourself would not be the best approach.
Libraries such as MomentJs implement methods such as moment.parseZone(), which appears to solve these problems for you.

How to insert the value of javascript into html [duplicate]

This question already has answers here:
How to Add Two Days from Current Date to the Value of a Hidden Input
(3 answers)
How to insert Javascript variables into a database
(1 answer)
Closed 5 years ago.
I want to get the javascript value into my html input value and insert it into the database after the user click the submit
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("display").innerHTML = someFormattedDate;
</script>
<?php
echo $_GET['someFormattedDate'];
?>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" value="<?php echo " someFormattedDate " style="border: 3px double #CCCCCC; " disabled/>
Since your input id is sd,
document.getElementById("sd").value = someFormattedDate;
Note: Elements with Disabled attribute are not submitted, enable it before submit.
Full Code:
<?php
echo $_GET['due_date'];
?>
<form name="myform" id="myform" method="GET">
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC; " readonly/>
<input type="submit" name="btn_submit" value="Submit">
</form>
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").value = someFormattedDate;
</script>
First, put the JavaScript code after the input you want to use. That way the input exists on the page when the code executes.
Second, use the actual id of the input.
Third, set the .value property.
Fourth, put the input in a form.
Fifth, don't disable the input.
Something like this:
<form>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" disabled/>
<input type="submit" value="Submit" />
</form>
<script>
// The rest of your JavaScript code, formatting your date value
document.getElementById("sd").value= someFormattedDate;
</script>
Unless otherwise specified, this <form> will submit a GET request to the current URL by default when the submit button is clicked.
Aside from that it's not really clear to me what you're trying to do with the PHP code here. Why you're trying to output a value that hasn't been submitted yet, or output a literal string, or whatever you're attempting.
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").innerHTML = someFormattedDate;
</script>
Description:- You are binding data with wrong element.

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