Logic behind creating a custom calendar in jquery and javascript - javascript

I am trying to wrap my head around the logic behind a calendar. At the moment, for testing purpose, I have displayed days with a counter (1-31), but 1 starts in the top left corner of the calendar. My question is, what do I need to do to calculate the current months days and display the month's days accordingly.
I have included some of my code.
this.RenderCalendar = function () {
var date = new Date();
date = new Date(date.getYear(), date.getMonth(), 1);
month = date.getMonth();
var calendarHeader = $("<div class=\"calHeader\"></div>");
var monthLabel = $("<label id=\"calMonth\">" + FRAMEWORK.GetMonthString(month) + "</label>");
var yearLabel = $("<label id=\"calYear\">" + date.getYear() + "</label>");
var nextMonth = $(">>");
var prevMonth = $("<<");
nextMonth.click(function () {
var oldTable = $(".calendarTableContainer table").first();
var newTable = FRAMEWORK.RenderCalendarTableMarkup(month + 1);
$(".calendarTableContainer").append(newTable);
$(".calendarTableContainer table").each(function () {
$(this).css("width", $(this).width() + "px");
});
$(".calendarTableContainer").css("width", ($(".calendarTableContainer table").outerWidth() * 2) + 25 + "px");
$(".calendarContainer").animate({
scrollLeft: $("div.calendarContainer").scrollLeft() + ($("div.calendarContainer table").next().width())
}, 500, function () {
$(".calendarTableContainer").css("width", "100%");
oldTable.remove();
$(".calendarTableContainer table").css("width", "100%");
});
var currentMonthIndex = $.inArray($("#calMonth").text(), months);
$("#calMonth").text(months[currentMonthIndex + 1]);
});
prevMonth.click(function () {
var oldTable = $(".calendarTableContainer table").first();
var newTable = FRAMEWORK.RenderCalendarTableMarkup(month - 1);
$(".calendarTableContainer").prepend(newTable);
$(".calendarTableContainer table").each(function () {
$(this).css("width", $(this).width() + "px");
});
$(".calendarTableContainer").css("width", ($(".calendarTableContainer table").outerWidth() * 2) + 25 + "px");
$(".calendarContainer").scrollLeft(oldTable.outerWidth());
$(".calendarContainer").animate({
scrollLeft: $("div.calendarContainer").scrollLeft() - ($("div.calendarContainer table").next().width())
}, 500, function () {
$(".calendarTableContainer").css("width", "100%");
oldTable.remove();
$(".calendarTableContainer table").css("width", "100%");
});
var currentMonthIndex = $.inArray($("#calMonth").text(), months);
$("#calMonth").text(months[currentMonthIndex - 1]);
});
calendarHeader.append(nextMonth);
calendarHeader.append(prevMonth);
calendarHeader.append(monthLabel);
calendarHeader.append(yearLabel);
$("#detailsContainer").append(calendarHeader);
var calendarContainer = $("<div class=\"calendarContainer\"></div>");
var calendarTableContainer = $("<div class=\"calendarTableContainer\"></div>");
calendarContainer.append(calendarTableContainer);
$("#detailsContainer").append(calendarContainer);
$(".calendarTableContainer").append(FRAMEWORK.RenderCalendarTableMarkup());
/*var containerHeight = $("#detailsContainer").height();
calendarContainer.css("height", containerHeight);
var calendarHeight = calendarContainer.outerHeight();
var calHeaderHeight = calendarHeader.outerHeight();
var calDayOfWeekHeight = $("#trCalDayOfWeekHeader").outerHeight();
var remainingContainerHeight = calendarHeight - calHeaderHeight - calDayOfWeekHeight;
$(".calendarContainer tr.trCalWeek").each(function () {
$(this).css("height", remainingContainerHeight / weekCount);
});*/
};
this.RenderCalendarTableMarkup = function (newMonth) {
var calendarTable = $("<table id=\"tabCalendar\" class=\"tabCalendarContainer\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\"></table>");
var calendarDayOfWeekHeader = $("<tr id=\"trCalDayOfWeekHeader\" class=\"trCalDayOfWeek\"></tr>");
for (var day = 0; day < days.length; day++) {
var dayOfWeek = $("<td id=\"tdDayName-" + days[day] + "\">" + days[day] + "</td>");
calendarDayOfWeekHeader.append(dayOfWeek);
};
calendarDayOfWeekHeader.find("td").each(function () {
$(this).css("width", 100 / 7 + "%");
});
calendarDayOfWeekHeader.find("td:last").css("border-right", "none");
calendarTable.append(calendarDayOfWeekHeader);
weekCount = FRAMEWORK.CountWeeksOfMonth(new Date().getDate(), month, new Date().getYear());
var dayCount = 1;
for (var week = 1; week <= weekCount; week++) {
var calendarWeek = $("<tr id=\"trWeek-" + week + "\" class=\"trCalWeek\"></tr>");
for (var day = 0; day < 7; day++) {
var calendarDay = $("<td id=\"tdDay-" + dayCount + "\"><label>" + dayCount + "</label></td>");
calendarWeek.append(calendarDay);
if (dayCount <= 30) {
dayCount++;
}
else { dayCount = 1; }
};
calendarWeek.find("td:last").css("border-right", "none");
calendarTable.append(calendarWeek);
};
return calendarTable;
};
RenderCalendar() gets called on dom ready. Within RenderCalendar, I have next- and previous month buttons which will navigate accordingly with RenderCalendarTableMarkup(), calculate the days and display them accordingly.
Any help please?

why do all this calculating by yourself anyway. Check out http://momentjs.com/

Related

How to change Excel Column Type in JS Script to Text before Exporting Data into Excel Sheet?

I am needing to convert 5 columns to TEXT before the program writes the data to it because Excel changes my 8 digit formatted date (MM/DD/YY) that gets outputted to those columns to the Date format (MM/DD/YYYY). The outputted date needs to stay in the 8 digit format in order to rerun it as the next input file to update the system. Any suggestions would be greatly appreciated. I have tried using:
ExcelSheet.ActiveSheet.Range("E:E").TextToColumns;
but it did not work. Here's all of the code:
<script>
function js_yyyy_mm_dd_hh_mm_ss () {
now = new Date();
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1);
if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate();
if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours();
if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes();
if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds();
if (second.length == 1) { second = "0" + second; }
return month + "" + day + "" + year.substring(2) + "" + hour + "" + minute + "" + second; }
function pad(num, len) { var str = '' + num; while (str.length < len) { str = '0' + str; } return str; } function writeToExcel() { try { var loanStr; var FullRecs; var passFail; var Processed = 0; var Rejected = 0; var D9ID; var time; var date; var datetime; var row = 0; var col; var str = document.getElementById("outstr").value; var headerStr = "|Account|Stop_Code_1|SC_1_Date|Stop_Code_2|SC_2_Date|Stop_Code_3|SC_3_Date|Lockout_Code|Lock_Date|Warning_Code|Warning_Date|"; var ExcelSheet = new ActiveXObject("Excel.Application"); var excelBook = ExcelSheet.Workbooks.Add; var RSheet = excelBook.Worksheets(1); ExcelSheet.Worksheets.Activate; ExcelSheet.ActiveSheet.Name = "Removals-" + js_yyyy_mm_dd_hh_mm_ss (); var outputdate = month + "-" + day + "-" + year.substring(2); var outputtime = hour + "-" + minute; var writefilepath = document.getElementById("writepath").value; var filepath = writefilepath.substring(0, writefilepath.lastIndexOf("\\") + 1); filepath = filepath + "DEL LOAN CODE Removal" + "_" + outputdate + "_" + outputtime + "_" + "OUTPUT" + ".xlsx"; date = month + "/" + day + "/" + year.substring(2); time = hour + ":" + minute + ":" + second; RSheet.Cells(1, 3).ColumnWidth = 15; RSheet.Cells(1, 4).ColumnWidth = 15; RSheet.Cells(1, 5).ColumnWidth = 15; RSheet.Cells(1, 6).ColumnWidth = 15; RSheet.Cells(1, 7).ColumnWidth = 15; RSheet.Cells(1, 8).ColumnWidth = 15; RSheet.Cells(1, 9).ColumnWidth = 15; RSheet.Cells(1, 10).ColumnWidth = 15; RSheet.Cells(1, 11).ColumnWidth = 15; RSheet.Cells(1, 12).ColumnWidth = 15; RSheet.Cells(1, 13).ColumnWidth = 15; ExcelSheet.ActiveSheet.Cells(1, 1).value = ""; var headings = headerStr.split("|"); for(var k = 0; k < (headings.length - 1); k ++ ) { ExcelSheet.ActiveSheet.Cells(7, k + 2).value = headings[k]; } FullRecs = str.split("~~"); for(var m = 0; m < (FullRecs.length - 1); m = m + 2) { loanStr = FullRecs[m].split("^"); for(var i = 0; i < (loanStr.length - 1); i ++ ) { var fieldStr = loanStr[i].split("|"); for(var j = 0; j < (fieldStr.length); j ++ ) { ExcelSheet.ActiveSheet.Cells(row + 8, j + 2).value = fieldStr[j]; } row = row + 1; } } for(var n = 1; n <= (FullRecs.length - 1); n = n + 2) { passFail = FullRecs[n].split("|"); D9ID = passFail[0]; Processed = Processed + Number(passFail[1]); Rejected = Rejected + Number(passFail[2]); } var total = Number(Processed) + Number(Rejected) ; ExcelSheet.ActiveSheet.Cells(2, 2).value = "USER"; ExcelSheet.ActiveSheet.Cells(2, 4).value = "SUMMARY"; ExcelSheet.ActiveSheet.Cells(3, 2).value = "DATE"; ExcelSheet.ActiveSheet.Cells(3, 3).value = date; ExcelSheet.ActiveSheet.Cells(4, 2).value = "TIME"; ExcelSheet.ActiveSheet.Cells(4, 3).value = time; ExcelSheet.ActiveSheet.Cells(2, 3).value = D9ID; ExcelSheet.ActiveSheet.Cells(3, 4).value = "PROCESSED ITEMS"; ExcelSheet.ActiveSheet.Cells(3, 5).value = + Processed; ExcelSheet.ActiveSheet.Cells(4, 4).value = "REJECTED ITEMS"; ExcelSheet.ActiveSheet.Cells(4, 5).value = + Rejected; ExcelSheet.ActiveSheet.Range("B2, B3, B4, D2, D3, D4, B7, C7, D7, E7, F7, G7, H7,I7,J7,K7,L7,M7").Font.Bold = true; for( var rb = 2; rb < 5; rb ++ ) { for( var cb = 2; cb < 6; cb ++ ) { RSheet.Cells(rb, cb).BorderAround(1).LineStyle = 1; } } for( var datarow = 7; datarow <= (7 + Number(total)); datarow ++ ) { for( var datacolumn = 3; datacolumn < 14; datacolumn ++ ) { RSheet.Cells(datarow, datacolumn).BorderAround(1).LineStyle = 1; } } ExcelSheet.ActiveSheet.Columns("A:P").HorizontalAlignment = 2; ExcelSheet.ActiveSheet.Range("C2", "C4").HorizontalAlignment = 3; ExcelSheet.ActiveSheet.Range("E2", "E4").HorizontalAlignment = 3; excelBook.SaveAs(filepath); ExcelSheet.Visible = false; ExcelSheet.UserControl = true; ExcelSheet.Application.Quit(); return true; } catch(e) { if(e.number == - 2146827284) { alert(e.description + ". Please close the document."); ExcelSheet.Application.Quit(); ExcelSheet.Quit(); ExcelSheet = null; return false; } } } </script>

Jquery Clone method increment name tag

Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}

Adding Google Calendar event end time to script

I have a script which lists Google Calendar events with the start time, name and description but I would like to have the end time too so it reads;
5:00pm - 6:00pm - Event title - event description
Rather than just what it has at the moment which is just the start time and not the end time.
This is the script I have:
$(document).ready(GCalEvents());
function GCalEvents() {
var datenow = new Date();
var curyear = datenow.getFullYear();
var curmonth = datenow.getMonth() + 1;
var curdate = datenow.getDate();
var curhour = datenow.getHours();
var curmin = datenow.getMinutes();
var curtz = datenow.getTimezoneOffset();
//curtz = -480;
var plusmin = "-";
if (curtz <= 0) {
plusmin = "%2B";
}
curtz = Math.abs(curtz);
var curtzmin = curtz % 60;
curtz = parseInt(curtz / 60);
if (curtzmin < 10) { curtzmin = "0" + curtzmin; }
if (curtz < 10) { curtz = "0" + curtz; }
datenow = curyear + "-" + curmonth + "-" + curdate + "T" + curhour + "%3A" + curmin + "%3A00" + plusmin + curtz + "%3A" + curtzmin;
var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
// var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
$.getJSON(url, function(data) {
var event_start_date_new = new Date();
event_start_date_new.setDate(event_start_date_new.getDate() - 1);
for(i in data['items']) {
item = data['items'][i];
// event title
var event_title = item.summary;
var event_description = item.description;
// event start date/time
var event_start_date = new Date(item.start.dateTime);
// format the date and time
var month = event_start_date.getMonth();
var day = event_start_date.getDay();
var date = event_start_date.getDate();
var daysArr = new Array();
daysArr[0] = "Sunday";
daysArr[1] = "Monday";
daysArr[2] = "Tuesday";
daysArr[3] = "Wednesday";
daysArr[4] = "Thursday";
daysArr[5] = "Friday";
daysArr[6] = "Saturday";
var monthsArr = new Array();
monthsArr[0] = "January";
monthsArr[1] = "February";
monthsArr[2] = "March";
monthsArr[3] = "April";
monthsArr[4] = "May";
monthsArr[5] = "June";
monthsArr[6] = "July";
monthsArr[7] = "August";
monthsArr[8] = "September";
monthsArr[9] = "October";
monthsArr[10] = "November";
monthsArr[11] = "December";
var hour = event_start_date.getHours();
var min = event_start_date.getMinutes();
if (min < 10) { min = "0" + min; }
if (hour < 11) {
var ampm = "am";
if (hour == 0) { hour = 12; }
} else {
var ampm = "pm";
if (hour > 12) { hour = hour - 12; }
}
if (hour < 10) { hour = " " + hour; }
var event_start_str = daysArr[day] + ", " + monthsArr[month] + " " + date;
var event_time_str = hour + ":" + min + " " + ampm;
if (event_start_date.getDate() != event_start_date_new.getDate()) {
event_start_str = "<div class=\"calendar_date\"><strong>" + event_start_str + "</strong></div>";
event_start_date_new = event_start_date;
} else {
event_start_str = "";
};
// Render the event
$("#gcal-events").last().before("<div class=\"calendar_item\"><li>" + event_time_str + " - " + event_title + "<p><small>" + event_description + "</small></p></ul>" + "</li></div>");
}
});
};
If anyone is able to help with that to reversion the current script, that would be great.
The Events resource returns start and end dates as well (JSON format that has date, dateTime, timeZone attributes).
Based on your code, you're not using the end attribute which is why you're not having any values for the end date displayed. Your code for the start date is alright, so you can just re-implement it for the end attribute.
Hope this helps!

Unable to Loading jquery datepicker on google maps

I am unable to load the datepicker on google maps
Here is the code
JS
function CreateMapTopControl(controlDiv, controlElement, controlId, map, event, response) {
controlDiv.style.padding = '5px';
var controlUI = document.createElement(controlElement);
controlUI.id = controlId;
controlDiv.appendChild(controlUI);
google.maps.event.addDomListener(controlUI, event, function() {
response();
return false;
});
return controlUI;
}
$(document).ready(function() {
maplct.initialize(document.getElementById('mapDiv'));
var dateDiv = document.createElement('div');
dateSel = new CreateMapTopControl(dateDiv, "input", "dateId", maplct.mapObject, "change", getMapRoute);
dateDiv.index = 2;
maplct.mapObject.controls[google.maps.ControlPosition.TOP].push(dateDiv);
$(dateSel).attr("type", "text")
$(dateSel).attr("style", "height:15px;width:100px;");
var curDate = new Date();
var d = curDate.getUTCDate();
var dd = (d < 10) ? "0" + d : d;
var m = curDate.getUTCMonth() + 1;
var mm = (m < 10) ? "0" + m : m;
var YYYY = curDate.getUTCFullYear();
var formattedDate = YYYY + "-" + mm + "-" + dd;
$(dateSel).val(formattedDate);
$(dateSel).datepicker({dateFormat: 'yy-mm-dd'});
$(dateSel).datepicker( "refresh" );
});
Map is getting loaded at the end of the file, it looks like css is not applied.

Unique ID that gets a date in specific format?

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I want it to add 1 each time the generateid button is clicked. so it will change to 0002. Here is the current code I have. Is there a function that can grab the date automatically?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
function Month() {
var m = new Date();
var mm = m.getMonth() + 1;
if (mm < 10) {
mm = '0' + mm;
return mm;
}
}
function Year() {
var y = new Date();
var yy = y.getFullYear();
return yy;
}
function Day() {
var d = new Date();
var dd = d.getDate();
return dd;
}
//generate id
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator();
document.getElementById("generateid").disabled = true;
}
You can use the following object:
var idGenerator = {
seq: 0,
generateId: function () {
this.seq++;
return (new Date()).toISOString().substring(0, 10) + '-' + ('000' + this.seq).substr(-4)
}
}
after declaration like this, try
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + idGenerator.generateId();
document.getElementById("generateid").disabled=true;
}
If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.
jsfiddle
var ttlIds = 0;
function guidGenerator() {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4());
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
//document.getElementById("generateid").disabled=true;
ttlIds++;
if(ttlIds < 10){
ttlIds_formatted = '000'+ttlIds;
}else if(ttlIds < 100){
ttlIds_formatted = '00'+ttlIds;
}else if(ttlIds < 1000){
ttlIds_formatted = '0'+ttlIds;
}
d = new Date();
var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
document.getElementById("funkydate").value = funkydate;
}

Categories

Resources