My datepicker doesn't work.
I have searched many questions that were similar to mine.
But I still couldn't find the solution.
I've only pasted the code that I think has some problems.
Here is my code in aspx:
It is in the script.
$(function () {
init();
});
function init() {
if (typeof $("#ContentPlaceHolder1_hidDepartDate").val() !== "undefined") {
var _dateStr = $("#ContentPlaceHolder1_hidDepartDate").val().substring(0, $("#ContentPlaceHolder1_hidDepartDate").val().length - 1);
var _dateStrArray = _dateStr.split(",");
}
$("#ContentPlaceHolder1_datepicker").datepicker({
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [_dateStrArray.indexOf(string) >= 0];
},
onSelect: function (selected, evnt) {
ChangeHiddenRadioButtonSelected(CTypeToDateString(selected));
},
inline: true
});
}
function CTypeToDateString(selected) {
var tempTime = selected.split("/");
var year = tempTime[2];
var month = tempTime[0];
var day = tempTime[1];
var yyyymmdd = year + "/" + month + "/" + day;
return yyyymmdd;
}
function ChangeHiddenRadioButtonSelected(SelectDate) {
var _dateCount = $("#ContentPlaceHolder1_hidDepartCount").val();
//alert(_dateCount);
var ServerDate = "";
for (var i = 0; i < parseInt(_dateCount); i++) {
ServerDate = $('label[for="ContentPlaceHolder1_rblDepartDate_' + i + '"]').html().substring(0, 10);
if (ServerDate == SelectDate) {
var radioItem = $('input[id="ContentPlaceHolder1_rblDepartDate_' + i + '"]');
if (radioItem) {
if (typeof $('input[id="ContentPlaceHolder1_rblDepartDate_' + i + '"]').attr("onclick") !== "undefined") {
if ($('input[id="ContentPlaceHolder1_rblDepartDate_' + i + '"]').attr("onclick").indexOf("no1") >= 0) {
alert('no2');
return false;
} else {
$('input[id="ContentPlaceHolder1_rblDepartDate_' + i + '"]').prop("checked", true);
}
} else {
$('input[id="ContentPlaceHolder1_rblDepartDate_' + i + '"]').prop("checked", true);
}
} else {
return false;
}
}
}
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(init);
There are all in the
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
The code of datepicker is
<div runat="server" id="datepicker"></div>
The pass from cs :
ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "bind", "init();", true);
I believe the problem is probably in this code.
Please help me.
Related
I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.
I need a datepicker for our project and whilst looking online.. I found one. However, it disables to allow future dates. I tried looking into the code but I cannot fully understand it. I'm kind of new to JQuery.
This is the code (it's very long, sorry):
<script>
$.datepicker._defaults.isDateSelector = false;
$.datepicker._defaults.onAfterUpdate = null;
$.datepicker._defaults.base_update = $.datepicker._updateDatepicker;
$.datepicker._defaults.base_generate = $.datepicker._generateHTML;
function DateRange(options) {
if (!options.startField) throw "Missing Required Start Field!";
if (!options.endField) throw "Missing Required End Field!";
var isDateSelector = true;
var cur = -1,prv = -1, cnt = 0;
var df = options.dateFormat ? options.dateFormat:'mm/dd/yy';
var RangeType = {ID:'rangetype',BOTH:0,START:1,END:2};
var sData = {input:$(options.startField),div:$(document.createElement("DIV"))};
var eData = {input:null,div:null};
/*
* Overloading JQuery DatePicker to add functionality - This should use WidgetFactory!
*/
$.datepicker._updateDatepicker = function (inst) {
var base = this._get(inst, 'base_update');
base.call(this, inst);
if (isDateSelector) {
var onAfterUpdate = this._get(inst, 'onAfterUpdate');
if (onAfterUpdate) onAfterUpdate.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]);
}
};
$.datepicker._generateHTML = function (inst) {
var base = this._get(inst, 'base_generate');
var thishtml = base.call(this, inst);
var ds = this._get(inst, 'isDateSelector');
if (isDateSelector) {
thishtml = $('<div />').append(thishtml);
thishtml = thishtml.children();
}
return thishtml;
};
function _hideSDataCalendar() {
sData.div.hide();
}
function _hideEDataCalendar() {
eData.div.hide();
}
function _handleOnSelect(dateText, inst, type) {
var localeDateText = $.datepicker.formatDate(df, new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
// 0 = sData, 1 = eData
switch(cnt) {
case 0:
sData.input.val(localeDateText);
eData.input.val('');
cnt=1;
break;
case 1:
if (sData.input.val()) {
var s = $.datepicker.parseDate(df,sData.input.val()).getTime();
var e = $.datepicker.parseDate(df,localeDateText).getTime();
if (e >= s) {
eData.input.val(localeDateText);
cnt=0;
}
}
}
}
function _handleBeforeShowDay(date, type) {
// Allow future dates?
var f = (options.allowFuture || date < new Date());
switch(type)
{
case RangeType.BOTH:
return [true, ((date.getTime() >= Math.min(prv, cur) && date.getTime() <= Math.max(prv, cur)) ?
'ui-daterange-selected' : '')];
case RangeType.END:
var s2 = null;
if (sData.input && sData.input.val()) {
try{
s2 = $.datepicker.parseDate(df,sData.input.val()).getTime();
}catch(e){}
}
var e2 = null;
if (eData.input && eData.input.val()) {
try {
e2 = $.datepicker.parseDate(df,eData.input.val()).getTime();
}catch(e){}
}
var drs = 'ui-daterange-selected';
var t = date.getTime();
if (s2 && !e2) {
return [(t >= s2 || cnt === 0) && f, (t===s2) ? drs:''];
}
if (s2 && e2) {
return [f, (t >= s2 && t <= e2) ? drs:''];
}
if (e2 && !s2) {
return [t < e2 && f,(t < e2) ? drs:''];
}
return [f,''];
}
}
function _attachCloseOnClickOutsideHandlers() {
$('html').click(function(e) {
var t = $(e.target);
if (sData.div.css('display') !== 'none') {
if (sData.input.is(t) || sData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideSDataCalendar();
}
}
if (eData && eData.div.css('display') !== 'none') {
if (eData.input.is(t) || eData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideEDataCalendar();
}
}
});
}
function _alignContainer(data, alignment) {
var dir = {right:'left',left:'right'};
var css = {
position: 'absolute',
top: data.input.position().top + data.input.outerHeight(true)
};
css[alignment ? dir[alignment]:'right'] = '0em';
data.div.css(css);
}
function _handleChangeMonthYear(year, month, inst) {
// What do we want to do here to sync?
}
function _focusStartDate(e) {
cnt = 0;
sData.div.datepicker('refresh');
_alignContainer(sData,options.opensTo);
sData.div.show();
_hideEDataCalendar();
}
function _focusEndDate(e) {
cnt = 1;
_alignContainer(eData,options.opensTo);
eData.div.datepicker('refresh');
eData.div.show();
sData.div.datepicker('refresh');
sData.div.hide();
}
// Build the start input element
sData.input.attr(RangeType.ID, options.endField ? RangeType.START : RangeType.BOTH);
sData.div.attr('id',sData.input.attr('id')+'_cDiv');
sData.div.addClass('ui-daterange-calendar');
sData.div.hide();
var pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
sData.input.before(pDiv);
pDiv.append(sData.input.detach());
pDiv.append(sData.div);
sData.input.on('focus', _focusStartDate);
sData.input.keydown(function(e){if(e.keyCode==9){return false;}});
sData.input.keyup(function(e){
_handleKeyUp(e, options.endField ? RangeType.START : RangeType.BOTH);
});
_attachCloseOnClickOutsideHandlers();
var sDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, options.endField ? RangeType.END : RangeType.BOTH);
},
onChangeMonthYear: _handleChangeMonthYear,
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,options.endField ? RangeType.END : RangeType.BOTH);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+sData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
sData.div.hide();
});
}
};
sData.div.datepicker($.extend({}, options, sDataOptions));
// Attach the end input element
if (options.endField) {
eData.input = $(options.endField);
if (eData.input.length > 1 || !eData.input.is("input")) {
throw "Illegal element provided for end range input!";
}
if (!eData.input.attr('id')) {eData.input.attr('id','dp_'+new Date().getTime());}
eData.input.attr(RangeType.ID, RangeType.END);
eData.div = $(document.createElement("DIV"));
eData.div.addClass('ui-daterange-calendar');
eData.div.attr('id',eData.input.attr('id')+'_cDiv');
eData.div.hide();
pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
eData.input.before(pDiv);
pDiv.append(eData.input.detach());
pDiv.append(eData.div);
eData.input.on('focus', _focusEndDate);
// Add Keyup handler
eData.input.keyup(function(e){
_handleKeyUp(e, RangeType.END);
});
var eDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, RangeType.END);
},
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,RangeType.END);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+eData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
eData.div.hide();
});
}
};
eData.div.datepicker($.extend({}, options, eDataOptions));
}
return {
// Returns an array of dates[start,end]
getDates: function getDates() {
var dates = [];
var sDate = sData.input.val();
if (sDate) {
try {
dates.push($.datepicker.parseDate(df,sDate));
}catch(e){}
}
var eDate = (eData.input) ? eData.input.val():null;
if (eDate) {
try {
dates.push($.datepicker.parseDate(df,eDate));
}catch(e){}
}
return dates;
},
// Returns the end date as a js date
getStartDate: function getStartDate() {
try {
return $.datepicker.parseDate(df,sData.input.val());
}catch(e){}
},
// Returns the start date as a js date
getEndDate: function getEndDate() {
try {
return $.datepicker.parseDate(df,eData.input.val());
}catch(e){}
}
};
}
var cfg = {startField: '#fromDate', endField: '#toDate',opensTo: 'Left', numberOfMonths: 3, defaultDate: -50};
var dr = new DateRange(cfg);
</script>
There is a comment along the code that says, "Allow Future Dates?" That's where I tried looking but I had no luck for hours now. Please help me.
This is how the date range picker looks like in my page:
Thank you so much for your help.
UPDATE: JSFIDDLE http://jsfiddle.net/dacrazycoder/4Fppd/
In cfg, add a property with key allowFuture with the value of true
http://jsfiddle.net/4Fppd/85/
I have this code below i am trying to get the id from within the click function but this.id does now work from within the click function i think because the code does not run until clicked does anyone know a way to get the id at the time the each loop runs?
$(html).each(function() {
if($( this ).filter('.target').html()){
window["button"+this.id] = {
text: "Edit "+$($(html).filter('#'+this.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#'+this.id).html()).filter('#B2').text());
var start = $($( html ).filter('#'+this.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#'+this.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#'+this.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#'+this.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#'+this.id).html()).filter('#A9').text();
if(PM == '1') { $('#PM').prop('checked', true); }else{ $('#PM').prop('checked', false); }
var NS = $($(html).filter('#'+this.id).html()).filter('#NS').text();
if(NS == '1') { $('#NS').prop('checked', true); }else{ $('#NS').prop('checked', false); }
var RDO = $($(html).filter('#'+this.id).html()).filter('#A12').text();
if(RDO == '1') { $('#RDO').prop('checked', true); }else{ $('#RDO').prop('checked', false); }
var OrdHours = $($(html).filter('#'+this.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#'+this.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#'+this.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#'+this.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#'+this.id).html()).filter('#A7').html();
$("#total").html(totalhrs +"<br />" +total);
adjustmentID = $($(html).filter('#'+this.id).html()).filter('#B1').text();
no_adjustment = false;
$( this ).dialog( "close" );
}
}
newArray.push(window["button"+this.id]);
}
});
Define this as a variable to keep your scope
var self = this;
full example below
$(html).each(function() {
var self = this;
if ($(self).filter('.target').html()) {
window["button" + self.id] = {
text: "Edit " + $($(html).filter('#' + self.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#' + self.id).html()).filter('#B2').text());
var start = $($(html).filter('#' + self.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#' + self.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#' + self.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#' + self.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#' + self.id).html()).filter('#A9').text();
if (PM == '1') {
$('#PM').prop('checked', true);
} else {
$('#PM').prop('checked', false);
}
var NS = $($(html).filter('#' + self.id).html()).filter('#NS').text();
if (NS == '1') {
$('#NS').prop('checked', true);
} else {
$('#NS').prop('checked', false);
}
var RDO = $($(html).filter('#' + self.id).html()).filter('#A12').text();
if (RDO == '1') {
$('#RDO').prop('checked', true);
} else {
$('#RDO').prop('checked', false);
}
var OrdHours = $($(html).filter('#' + self.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#' + self.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#' + self.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#' + self.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#' + self.id).html()).filter('#A7').html();
$("#total").html(totalhrs + "<br />" + total);
adjustmentID = $($(html).filter('#' + self.id).html()).filter('#B1').text();
no_adjustment = false;
$(self).dialog("close");
}
}
newArray.push(window["button" + self.id]);
}
});
I really like this calendar plugin for my mobile site: https://github.com/michaelkamphausen/jsCalendar
Seen working here: http://jsfiddle.net/dQxVV/1/
I am pretty new at JS and am having trouble figuring out
How to collect the selected start and end dates (place them into an input value)
How to show more than one month.
I really appreciate any help on this or if you have a suggestion for a better mobile friendly calendar.
JS building date range calendar:
$(".jsCalendar").bind("startDateChanged", function () {
$(this).data("startdate");
}).bind("endDateChanged", function () {
$(this).data("enddate");
});
calendar.js
(function() {
$(document).ready(function() {
var $calendars = $(".jsCalendar");
for (var i = 0, maxI = $calendars.length; i < maxI; i++) {
var calendar = new Calendar();
calendar.ready($calendars.eq(i));
}
});
function Calendar() {
var self = this,
$calendar,
$previous,
$next,
$month,
$weekdays,
$days,
$rows,
startDate,
endDate,
currentMonth,
today,
minDate,
dateInfo,
singleDate,
firstDayOfWeek = 0,
tap = 'click',
noAnimEnd = "noAnimationEnd",
startDateString = "startDate",
endDateString = "endDate",
setDate = function (type, value) {
value && value.clearTime && value.clearTime();
if (type == startDateString) {
startDate = value;
} else {
endDate = value;
}
drawSelection();
$calendar.data(type.toLowerCase(), !value ? "" : value.toString());
$calendar.trigger(type + "Changed");
},
dateSelected = function (evt) {
evt.preventDefault();
var $this = $(this);
if ($this.hasClass("inactive") || ($this.text().length == 0)) {
return;
}
var selectedDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), parseInt($this.text()));
if (singleDate) {
setDate(startDateString, !startDate || (selectedDate.getTime() != startDate.getTime()) ? selectedDate : null);
return;
}
if (!startDate) {
if (!endDate) {
setDate(startDateString, selectedDate);
} else {
if (selectedDate < endDate) {
setDate(startDateString, selectedDate);
} else if (endDate < selectedDate) {
setDate(startDateString, endDate);
setDate(endDateString, selectedDate);
} else {
setDate(endDateString, null);
}
}
} else if (!endDate) {
if (startDate < selectedDate) {
setDate(endDateString, selectedDate);
} else if (selectedDate < startDate) {
setDate(endDateString, startDate);
setDate(startDateString, selectedDate);
} else {
setDate(startDateString, null);
}
} else {
if ($this.hasClass(startDateString)) {
setDate(startDateString, null);
} else if ($this.hasClass(endDateString)) {
setDate(endDateString, null);
} else {
setDate(startDateString, null);
setDate(endDateString, null);
}
}
},
extendDate = function () {
/* subset from date.js, http://www.datejs.com/ */
Date.prototype.clone=function(){return new Date(this.getTime());}
Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));}
Date.prototype.getDaysInMonth=function(){return [31,(this.isLeapYear(this.getFullYear())?29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];}
Date.prototype.moveToFirstDayOfMonth=function(){this.setDate(1);return this;}
Date.prototype.moveToLastDayOfMonth=function(){this.setDate(this.getDaysInMonth());return this;}
Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;}
Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);}
Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;}
Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;}
},
getDay = function (day) {
return (day + firstDayOfWeek) % 7; // changing first day of week
},
drawSelection = function () {
$days.removeClass(startDateString).removeClass(endDateString).removeClass("betweenDates");
var firstDay = currentMonth.clone().moveToFirstDayOfMonth();
var lastDay = currentMonth.clone().moveToLastDayOfMonth();
var dayOffset = getDay(firstDay.getDay()) - 1;
if (!!startDate && !!endDate && (startDate < lastDay) && (endDate > firstDay)) {
var firstBetweenDay = new Date(Math.max(firstDay, startDate.clone().addDays(1)));
var lastBetweenDay = new Date(Math.min(lastDay, endDate.clone().addDays(-1)));
if (firstBetweenDay <= lastBetweenDay) {
$days.slice(dayOffset + firstBetweenDay.getDate(), dayOffset + lastBetweenDay.getDate() + 1).addClass("betweenDates");
}
}
if (!!startDate && (firstDay <= startDate) && (startDate <= lastDay)) {
$days.eq(dayOffset + startDate.getDate()).addClass(startDateString);
}
if (!!endDate && (firstDay <= endDate) && (endDate <= lastDay)) {
$days.eq(dayOffset + endDate.getDate()).addClass(endDateString);
}
};
self.ready = function ($element) {
$calendar = $element;
$previous = $('<');
$next = $('>');
$month = $('<li class="calMonth"></li>');
$calendar.append($('<ul class="calButtonBar"></ul>')
.append($('<li class="calPrevious"></li>').append($previous))
.append($month)
.append($('<li class="calNext"></li>').append($next))
);
for (var i = 0, th = "", td = ""; i < 7; i++) {
th += '<th></th>';
td += '<td></td>';
}
for (var i = 0, tr = ""; i < 6; i++) {
tr += '<tr>' + td + '</tr>';
}
$calendar.append('<div class="calGrid"><table><tr>' + th + '</tr>' + tr + '</table></div>');
$weekdays = $calendar.find("th");
$days = $calendar.find("td a");
$rows = $calendar.find("tr");
$rows.eq(1).addClass("first");
singleDate = $calendar.hasClass("jsSingleDate");
firstDayOfWeek = $calendar.data("firstdayofweek") || firstDayOfWeek;
$calendar.get(0).calendar = self;
if ($.fn) {
$.fn.slice = $.fn.slice || function (start, end) {
return $([].slice.call(this, start, end));
}
$.fn.calendar = function() {
return this.get(0).calendar;
}
}
extendDate();
today = (new Date()).clearTime();
minDate = today;
startDate = $calendar.data("startdate");
startDate = startDate ? new Date(startDate).clearTime() : null;
endDate = $calendar.data("enddate");
endDate = endDate ? new Date(endDate).clearTime() : null;
currentMonth = (startDate || today).clone();
dateInfo = $calendar.data("localized_date");
if (typeof dateInfo == "string") {
dateInfo = JSON.parse(dateInfo);
}
var $monthGrid = $calendar.find(".calGrid");
var animationQueue = [];
var isAnimating = function(node) {
if ($monthGrid.children().length > 1) {
animationQueue.push(node);
return true;
}
return false;
}
var nextAnimation = function() {
if (animationQueue.length > 0) {
setTimeout(function() {
animationQueue.shift().trigger(tap);
}, 0);
}
}
$previous.bind(tap, function (evt) {
evt.preventDefault();
if (isAnimating($previous)) return;
currentMonth = currentMonth.addMonths(-1);
var $page = $('<table>' + $calendar.find("table").html() + '</table>');
$monthGrid.append($page);
$days.closest("table").addClass("turndown").bind(animEnd, function (evt) {
$(this).removeClass("turndown").unbind(animEnd);
$page.remove();
nextAnimation();
}).trigger(noAnimEnd);
self.showMonth(currentMonth);
});
$next.bind(tap, function (evt) {
evt.preventDefault();
if (isAnimating($next)) return;
currentMonth = currentMonth.addMonths(+1);
var $page = $('<table class="turnup">' + $calendar.find("table").html() + '</table>');
$monthGrid.append($page);
$page.bind(animEnd, function (evt) {
$page.remove();
nextAnimation();
}).trigger(noAnimEnd);
self.showMonth(currentMonth);
});
$calendar.bind("resetDates", function (evt) {
setDate(startDateString, null);
setDate(endDateString, null);
});
$days.bind(tap, dateSelected);
self.showMonth(currentMonth);
}
self.setDates = function(start, end) {
setDate(startDateString, start && end ? new Date(Math.min(start, end)) : start);
!singleDate && setDate(endDateString, start && end ?
(start.getTime() != end.getTime() ? new Date(Math.max(start, end)) : null) : end);
}
self.showMonth = function (date) {
minDate = new Date(Math.max(minDate, today));
if (!!dateInfo) {
$month.text(dateInfo.months.names["long"][date.getMonth()] + " " + date.getFullYear());
for (var i = 0, maxI = $weekdays.length; i < maxI; i++) {
$weekdays.eq(getDay(i)).text(dateInfo.days.names.min[i]);
}
}
var beforeMinDate = minDate > date.clone().moveToLastDayOfMonth();
var includesToday = !beforeMinDate && (minDate >= date.clone().moveToFirstDayOfMonth());
var minDay = minDate.getDate();
$days.addClass("noTransition").removeClass("inactive");
$rows.removeClass("last").removeClass("hidden");
for (var firstDay = getDay(date.clone().moveToFirstDayOfMonth().getDay()) - 1, lastDay = firstDay + date.clone().moveToLastDayOfMonth().getDate(), i = 0, maxI = $days.length; i < maxI; i++) {
var isDay = (i > firstDay) && (i <= lastDay);
var $day = $days.eq(i).text(isDay ? ("" + (i - firstDay)) : "");
if (isDay && (beforeMinDate || (includesToday && (i - firstDay < minDay)))) {
$day.addClass("inactive");
}
if (includesToday && today.getDate() == (i - firstDay)) {
$day.addClass("today");
}
if (i == lastDay) {
$day.closest("tr").addClass("last").next().addClass("hidden").next().addClass("hidden");
}
}
setTimeout(function() {
$days.removeClass("noTransition");
}, 0);
drawSelection();
}
}
})()
The code you posted turns any div with a class of jsCalendar into a jsCalendar.
You're going to want to assign an individual id to any jsCalendar object you want to access the dates of.
You should be able to see what 2 dates the user has selected by calling the data function on the jsCalendar object. For instance, if you had a jsCalendar with an id of jsCalendar1:
var startDate = $("#jsCalendar1").data("startdate");
var endDate = $("#jsCalendar1").data("enddate");
alert("Calendar 1 has a start date of " + startDate + " and an end date of " + endDate + ".");
Make sure you put this code somewhere appropriate, such as in a function that isn't called until after a user has selected a start and end date.
Here's a working jsFiddle.
I'm a beginner in Javascript and I'm having some trouble with this code I wrote. It's supposed to create a digital time-clock for my website.
If you're wondering why CPGS is in my functions/variable names it's because its a abbreviation for my website name :)
Also, I am getting NO console errors from FireBug and my JSLint confirms that my code is vaild.
Here's the code:
(function() {
function CpgsClock() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
}
CpgsClock.prototype.checker = function() {
if (this.cpgsHour === 0) {
this.cpgsPeriod = " AM";
this.cpgsHour = 12;
} else if (this.cpgsHour <= 11) {
this.cpgsPeriod = " AM";
} else if (this.cpgsHour === 12) {
this.cpgsPeriod = " PM";
} else if (this.cpgsHour <= 13) {
this.cpgsPeriod = " PM";
this.cpgsHour -= 12;
}
};
CpgsClock.prototype.setClock = function() {
document.getElementById('cpgstime').innerHTML = "" + this.cpgsHour + ":" + this.cpgsMin + this.cpgsPeriod + "";
};
var cpgsclock = new CpgsClock();
setInterval(function() {
cpgsclock.setClock();
cpgsclock.checker();
}, 1000);
})();
So setClock method works fine. But the checker won't do anything. As you can see it checks for the time and sets it to AM and PM accordingly. It doesn't do that for me.
Any help would be great!
You're not updating the clock in your setInterval...
CpgsClock.prototype.update = function() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
};
And in your setInterval :
setInterval(function() {
cpgsclock.update();
cpgsclock.checker();
cpgsclock.setClock();
}, 1000);
jsFiddle : http://jsfiddle.net/qmSua/1/