Cant get what's the issue with Datepicker? - javascript

I'm using smarty template engine. I'm using datepicker js plugin. My HTML code is as follows:
<tr>
<td valign="middle" align="right"><b>From Date </b> : </td>
<td align="left" > <input type="text" style="width:100px;" class="inputfield" name="from_date" id="from_date" value="{$from_date}" maxlength="10"/></td>
<td valign="middle" align="right"><b>To Date </b> : </td>
<td> <input type="text" style="width:100px;" class="inputfield" name="to_date" id="to_date" value="{$to_date}" maxlength="10"/></td>
</tr>
The jQuery function code is as below :
{literal}
<script language="javascript" type="application/javascript">
$(function() {
$( "#from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(function() {
$( "#to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(document).ready(function() {
$("#questions_listing").tablesorter({
widgets:['zebra'],
// sort on the fourth column and first column, order asc
sortList: [[1,0]]
});
});
$(".submit_form").click(function(e) {
var result = validateDate();
if(!result)
return false;
else
document.questions_filter.submit();
});
</script>
{/literal}
The datepicker.js file is as follows:
/* $(function() {
$( "#cal_from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
$( "#cal_to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});*/
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "dmy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function refreshDatePicker(dateFieldName, year, month, day)
{
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_buttons = "<td class='dpButtonTD'>";
var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "<") + xTD;
html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, ">") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArrayShort.length; i++)
html += TD_days + dayArrayShort[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + " " + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + " " + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
// after the datepicker has closed, optionally run a user-defined function called
// datePickerClosed, passing the field that was just updated as a parameter
// (note that this will only run if the user actually selected a date from the datepicker)
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// we know that Opera doesn't like something about this, so if we
// think we're using Opera, don't even try
var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if (is_opera)
return;
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}
When I tested in firbug it is giving me the error TypeError: $(...).datepicker is not a function
I've included the files reuired i.e. jquery1.9.1 and datepicker .js, but still it's not working. Can anyone help me to resolve this issue?

Your code is just working perfectly! Check out this.
You just missed to include jquery-ui
Try including : <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> in you <head> tag.
UPDATE: The fiddle is by #Safiuddin

Related

Ignore Sundays from jQuery date range picker

I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/

How can I execute a external JS from HTML every 10 min?

I have a HMTL which execute a external JS. The JS returns my Google Calender events. I want my calender to be updated automatically every 10minutes.
The HTML looks like:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="format-google-calendar.js"></script>
<script>
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
</script>
The JS looks like:
var formatGoogleCalendar = (function() {
'use strict';
var config;
//Gets JSON from Google Calendar and transfroms it into html list items and appends it to past or upcoming events list
var init = function(settings) {
var result = [];
config = settings;
var finalURL = settings.calendarUrl;
if(settings.recurringEvents) finalURL = finalURL.concat("&singleEvents=true");
//Get JSON, parse it, transform into list items and append it to past or upcoming events list
jQuery.getJSON(finalURL, function(data) {
// Remove any cancelled events
data.items.forEach(function removeCancelledEvents(item) {
if (item && item.hasOwnProperty('status') && item.status !== 'cancelled') {
result.push(item);
}
});
result.sort(comp).reverse();
var pastCounter = 0,
upcomingCounter = 0,
pastResult = [],
upcomingResult = [],
upcomingResultTemp = [],
$upcomingElem = jQuery(settings.upcomingSelector),
$pastElem = jQuery(settings.pastSelector),
i;
if (settings.pastTopN === -1) {
settings.pastTopN = result.length;
}
if (settings.upcomingTopN === -1) {
settings.upcomingTopN = result.length;
}
if (settings.past === false) {
settings.pastTopN = 0;
}
if (settings.upcoming === false) {
settings.upcomingTopN = 0;
}
for (i in result) {
if (isPast(result[i].end.dateTime || result[i].end.date)) {
if (pastCounter < settings.pastTopN) {
pastResult.push(result[i]);
pastCounter++;
}
} else {
upcomingResultTemp.push(result[i]);
}
}
upcomingResultTemp.reverse();
for (i in upcomingResultTemp) {
if (upcomingCounter < settings.upcomingTopN) {
upcomingResult.push(upcomingResultTemp[i]);
upcomingCounter++;
}
}
for (i in pastResult) {
$pastElem.append(transformationList(pastResult[i], settings.itemsTagName, settings.format));
}
for (i in upcomingResult) {
$upcomingElem.append(transformationList(upcomingResult[i], settings.itemsTagName, settings.format));
}
if ($upcomingElem.children().length !== 0) {
jQuery(settings.upcomingHeading).insertBefore($upcomingElem);
}
if ($pastElem.children().length !== 0) {
jQuery(settings.pastHeading).insertBefore($pastElem);
}
});
};
//Compare dates
var comp = function(a, b) {
return new Date(a.start.dateTime || a.start.date).getTime() - new Date(b.start.dateTime || b.start.date).getTime();
};
//Overwrites defaultSettings values with overrideSettings and adds overrideSettings if non existent in defaultSettings
var mergeOptions = function(defaultSettings, overrideSettings){
var newObject = {},
i;
for (i in defaultSettings) {
newObject[i] = defaultSettings[i];
}
for (i in overrideSettings) {
newObject[i] = overrideSettings[i];
}
return newObject;
};
var isAllDay = function (dateStart, dateEnd) {
var dateStartFormatted = getDateFormatted(dateStart),
dateEndFormatted = getDateFormatted(dateEnd);
//if start date is midnight and the end date a following day midnight as well
if ((dateStartFormatted.getTime() === dateEndFormatted.getTime() - 86400000) &&
dateStartFormatted.getMinutes() === 0 &&
dateStartFormatted.getHours() === 0) {
return true;
}
return false;
};
//Get all necessary data (dates, location, summary, description) and creates a list item
var transformationList = function(result, tagName, format) {
var dateStart = getDateInfo(result.start.dateTime || result.start.date),
dateEnd = getDateInfo(result.end.dateTime || result.end.date),
moreDaysEvent = (typeof result.end.date !== 'undefined'),
dayNames = config.dayNames,
isAllDayEvent = isAllDay(dateStart, dateEnd);
if (moreDaysEvent) {
dateStart = addOneDay(dateStart);
}
if (isAllDayEvent) {
dateEnd = subtractOneMinute(dateEnd);
}
var dateFormatted = getFormattedDate(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames),
output = '<' + tagName + '>',
summary = result.summary || '',
description = result.description || '',
location = result.location || '',
i;
for (i = 0; i < format.length; i++) {
format[i] = format[i].toString();
if (format[i] === '*summary*') {
output = output.concat('<span class="summary">' + summary + '</span>');
} else if (format[i] === '*date*') {
output = output.concat('<span class="date">' + dateFormatted + '</span>');
} else if (format[i] === '*description*') {
output = output.concat('<span class="description">' + description + '</span>');
} else if (format[i] === '*location*') {
output = output.concat('<span class="location">' + location + '</span>');
} else {
if ((format[i + 1] === '*location*' && location !== '') ||
(format[i + 1] === '*summary*' && summary !== '') ||
(format[i + 1] === '*date*' && dateFormatted !== '') ||
(format[i + 1] === '*description*' && description !== '')) {
output = output.concat(format[i]);
}
}
}
return output + '</' + tagName + '>';
};
//Check if date is later then now
var isPast = function(date) {
var compareDate = new Date(date),
now = new Date();
if (now.getTime() > compareDate.getTime()) {
return true;
}
return false;
};
//Get temp array with information abou day in followin format: [day number, month number, year, hours, minutes]
var getDateInfo = function(date) {
date = new Date(date);
return [date.getDate(), date.getMonth(), date.getFullYear(), date.getHours(), date.getMinutes(), 0, 0];
};
//Get month name according to index
var getMonthName = function (month) {
var monthNames = [
'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli',
'August', 'September', 'Oktober', 'November', 'Dezember'
];
return monthNames[month];
};
var getDayName = function (day) {
var dayNames = [
'Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'
];
return dayNames[day];
};
var getDayNameFormatted = function (dateFormatted) {
return getDayName(getDateFormatted(dateFormatted).getDay()) + ' ';
};
var getDateFormatted = function (dateInfo) {
return new Date(dateInfo[2], dateInfo[1], dateInfo[0], dateInfo[3], dateInfo[4] + 0, 0);
};
//Add one day
var addOneDay = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() + 86400000);
return getDateInfo(date);
};
//Subtract one day
var subtractOneDay = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() - 86400000);
return getDateInfo(date);
};
//Subtract one minute
var subtractOneMinute = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() - 60000);
return getDateInfo(date);
};
//Transformations for formatting date into human readable format
var formatDateSameDay = function(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames) {
var formattedTime = '',
dayNameStart = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
}
if (config.sameDayTimes && !moreDaysEvent && !isAllDayEvent) {
formattedTime = ' from ' + getFormattedTime(dateStart) + ' - ' + getFormattedTime(dateEnd);
}
//month day, year time-time
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2] + formattedTime;
};
var formatDateOneDay = function(dateStart, dayNames) {
var dayName = '';
if (dayNames) {
dayName = getDayNameFormatted(dateStart);
}
//month day, year
return dayName + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2];
};
var formatDateDifferentDay = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day-day, year
return dayNameStart + getMonthName(dateStart[1]) + ' ' + dateStart[0] + '-' + dayNameEnd + dateEnd[0] + ', ' + dateStart[2];
};
var formatDateDifferentMonth = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day - month day, year
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ' ' + '-' + dayNameEnd + dateEnd[0] + '. ' + getMonthName(dateEnd[1]) + ', ' + dateStart[2];
};
var formatDateDifferentYear = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day, year - month day, year
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2] + '-' + dayNameEnd + dateEnd[0] + '. ' + getMonthName(dateEnd[1]) + ', ' + dateEnd[2];
};
//Check differences between dates and format them
var getFormattedDate = function(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames) {
var formattedDate = '';
if (dateStart[0] === dateEnd[0]) {
if (dateStart[1] === dateEnd[1]) {
if (dateStart[2] === dateEnd[2]) {
//month day, year
formattedDate = formatDateSameDay(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
} else {
if (dateStart[2] === dateEnd[2]) {
//month day - month day, year
formattedDate = formatDateDifferentMonth(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
}
} else {
if (dateStart[1] === dateEnd[1]) {
if (dateStart[2] === dateEnd[2]) {
//month day-day, year
formattedDate = formatDateDifferentDay(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
} else {
if (dateStart[2] === dateEnd[2]) {
//month day - month day, year
formattedDate = formatDateDifferentMonth(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
}
}
return formattedDate;
};
var getFormattedTime = function (date) {
var formattedTime = '',
period = 'Uhr',
hour = date[3],
minute = date[4];
// Handle afternoon.
if (hour >= 12) {
period = 'Uhr';
}
// Handle midnight.
if (hour === 0) {
hour = 0;
}
// Ensure 2-digit minute value.
minute = (minute < 10 ? '0' : '') + minute;
// Format time.
formattedTime = hour + ':' + minute + period;
return formattedTime;
};
return {
init: function (settingsOverride) {
var settings = {
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/milan.kacurak#gmail.com/events?key=AIzaSyCR3-ptjHE-_douJsn8o20oRwkxt-zHStY',
past: true,
upcoming: true,
sameDayTimes: true,
dayNames: true,
pastTopN: -1,
upcomingTopN: -1,
recurringEvents: true,
itemsTagName: 'li',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<h2>Upcoming events</h2>',
pastHeading: '<h2>Past events</h2>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
};
settings = mergeOptions(settings, settingsOverride);
init(settings);
}
};
})();
Can you explain me based on my code how I can re-run the js every 10min? I am not sure where I have to put setIntervall(?????????,10*60*1000)?
Try to put formatGoogleCalendar.init() in a setInterval, like this :
setInterval(function(){
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
}, 600000);
Move your init into a function and call that function in the setInterval() every 10 minutes.
<script>
function calendarInit(){
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
}
var cal = setInterval(calendarInit(), 10*60*1000);
Well you can use
setInterval(function, delay)
delay is in milliseconds and function is the name of the function you want to call. Therefore, you need to wrap your content of js file within a function as
function callAgain()
{
var formatGoogleCalendar = (function() {
'use strict';
var config;
.
.
.
}
and then use the setInterval(callAgain, 5000) in the script part of your html file

How to clear div content onclick? [duplicate]

This question already has answers here:
How do I clear the content of a div using JavaScript? [closed]
(2 answers)
Closed 7 years ago.
I'm making a calendar purely from Javascript, but when then previous and next months are shown current content is still present. It should replace the div content. Also, current date should be the only one with red font displayed.
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.write(text);
}
</script></head>
<body onload="setCal()">
</body>
</html>
I think it will be better if you can use a container element and set its content rather than to use document.write()
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.getElementById('calc').innerHTML=text;
}
</script></head>
<body onload="setCal()">
<div id="calc"></div>
</body>
</html>
if you want to clear any HTML element you would just
DO NOT use document.write() it clears the whole page.
It's the document.write() It always stays there no matter what. Try not to use document.write()
use createElement('div') instead. It's much more clean, you can keep track of the elements, and they're static, unless you want them to change. everything is under your control.
document.getElementById('Clear_This_Div_id').innerHTML = '';
This will usually clear the element
Without changing much of the other part of your code, you can just change the
document.write(text);
to
document.getElementsByTagName('body')[0].innerHTML = text;
This will clear off the previous content before putting the new one, since you are putting in the body every time.

Increment a value if ... Javascript

I am working on a small piece of code that looks to see if a value is equal to 'December 25 - January 9' and if it does increment the year (that I append to it) by one
However I can not figure out how to find that value. Every time I run the script it skips to the else part of the script when that value is selected.
Any guidance is appreciated
if ($('#date').val === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('year').val;
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
Problem is you are using JQuery but chexking value as in javascript
$('#date')[0].value === 'December 25 - January 9'
or
$('#date').val() === 'December 25 - January 9'
should do it.
I see two places where you used val instead of val(), you want to call the function val not access a non-existent val field
if ($('#date').val() === 'December 25 - January 9') { // <-- val()
var startDates = $('#date').val().split(" - ");
var year = $('year').val(); // <-- val()
Try this. It should work.
You have var should be var() also year should be #year
if ($('#date').val() === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
console.log(startDates);
console.log(year);
console.log(yearDec);
console.log(payPdStart);
console.log(payPdEnd);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + " </td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}

Jquery mobile input in collapsilble problem

I have a list of collapsible times like in screen shot.. and a droplist.. in drop list you can choose the time how collapsible will separate times.. When i open activity first time...it's working fine but when i choose another time in droplist and he update collapsibles input loses their style and not working..
here is droplist change event->>
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
and here is draw collapsibles function->>
function drawTemplate() {
var selectedValue = parseInt($('#timeDropList').val());
var textProjectName = '<input type="text" class="projectName" value="" />';
var textProjectData = '<input style="height:50px;" type="text" class="projectEntry" value="" />';
var timespan;
if ($('.div-cell').hasClass('tapped')) {
var calToScheDate = $('.div-cell.tapped').find('.dayNumberCellValue')
.attr('data-a');
var calToScheMonth;
var calToScheDay;
if (calToScheDay = calToScheDate.substring(6, 8) < 10) {
calToScheDay = calToScheDate.substring(7, 8);
} else {
calToScheDay = calToScheDate.substring(6, 8);
}
if (calToScheMonth = calToScheDate.substring(4, 6) < 10) {
calToScheMonth = calToScheDate.substring(5, 6);
} else {
calToScheMonth = calToScheDate.substring(4, 6);
}
timespan = new Date(calToScheDate.substring(0, 4), calToScheMonth,
calToScheDay, 9, 0);
} else {
timespan = new Date();
timespan = new Date(timespan.getFullYear(), timespan.getMonth(),
timespan.getDate(), 9, 0);
}
while (timespan.getHours() < 18 || timespan.getHours() == 18
&& timespan.getMinutes() == 0) {
var hoursFrom = timespan.getHours();
var minsFrom = timespan.getMinutes();
if (minsFrom < 10) {
minsFrom = "0" + minsFrom;
}
if (hoursFrom < 10) {
hoursFrom = "0" + hoursFrom;
}
var hoursTo = timespan.getHours();
var minsTo = timespan.getMinutes() + selectedValue
if (minsTo == 60) {
minsTo = "00";
hoursTo++;
} else if (minsTo < 10) {
minsTo = "0" + minsTo;
}
var collDiv = '<div class="addedEntry" data-theme="c" data-role="collapsible" id='+hoursFrom+minsFrom+hoursTo+minsTo+' data-collapsed="true"><h3 class="results-header">'
+ hoursFrom
+ ":"
+ minsFrom
+ " - "
+ hoursTo
+ ":"
+ minsTo +'</h3>' + '</div>';
$('.spanTimetable').append(collDiv);
timespan.setMinutes(timespan.getMinutes() + selectedValue);
}
$('.addedEntry').append(textProjectName);
$('.addedEntry').append(textProjectData);
$('.results-header').append('<img class="checkOrCross" />');
$('#timetable .addedEntry').collapsible({
refresh : true
});
}
You will need to refresh the jQM using .page()
Maybe try:
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
$('#name of your page').page();

Categories