Wordpress Plugin functions, only one works? - javascript

So I have a plugin on wordpress with an in-built calendar.
The developer has given instructions on how to remove the option to select past dates, and also specific dates of your choosing.
http://support.themecatcher.net/quform-wordpress/guides/advanced/date-validation
I have followed the instructions, but perhaps I'm missing something. As only one of the functions work at a time, but never both at the same time.
Here is the code. Any help would be greatly appreciated. Thanks!
function my_prevent_past_dates($valid, $value, $element)
{
$time = strtotime("{$value['year']}-{$value['month']}-{$value['day']}");
if ($time < strtotime('today')) {
$element->addError('Please choose a date in the future');
$valid = false;
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_past_dates', 10, 3);
function my_datepicker_prevent_past_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
minDate: 0,
maxDate: new Date({$dpMaxYear}, 12 - 1, 31)
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_past_dates', 10, 4);
function my_get_dates_to_disable()
{
return array(
'2015-05-1',
'2015-05-2',
'2015-05-3',
'2015-05-4',
'2015-05-5',
'2015-05-6',
);
}
function my_prevent_specific_dates($valid, $value, $element)
{
if ($valid) {
$disabledDates = my_get_dates_to_disable();
$submittedDate = "{$value['year']}-{$value['month']}-{$value['day']}";
if (in_array($submittedDate, $disabledDates)) {
$element->addError('That date is not available');
$valid = false;
}
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_specific_dates', 10, 3);
function my_datepicker_prevent_specific_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
beforeShowDay: function (date) {
if (quformDisabledDates) {
for (var i = 0; i < quformDisabledDates.length; i++) {
var parts = quformDisabledDates[i].split('-');
if (date.getFullYear() == parts[0] && (date.getMonth()+1) == parts[1] && date.getDate() == parts[2]) {
return [false];
}
}
}
return [true];
}
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_specific_dates', 10, 4);
function my_print_dates_to_disable()
{
?>
<script type="text/javascript">
var quformDisabledDates = <?php echo json_encode(my_get_dates_to_disable()); ?>;
</script>
<?php
}
add_action('wp_head', 'my_print_dates_to_disable');

You can combine my_prevent_past_dates with my_prevent_specific_dates, and my_datepicker_prevent_past_dates with my_datepicker_prevent_specific_dates.
function my_get_dates_to_disable()
{
return array(
'2015-05-1',
'2015-05-2',
'2015-05-3',
'2015-05-4',
'2015-05-5',
'2015-05-6',
);
}
function my_prevent_bad_dates($valid, $value, $element)
{
$time = strtotime("{$value['year']}-{$value['month']}-{$value['day']}");
if ($time < strtotime('today')) {
$element->addError('Please choose a date in the future');
$valid = false;
} else {
$disabledDates = my_get_dates_to_disable();
$submittedDate = "{$value['year']}-{$value['month']}-{$value['day']}";
if (in_array($submittedDate, $disabledDates)) {
$element->addError('That date is not available');
$valid = false;
}
}
return $valid;
}
add_filter('iphorm_element_valid_iphorm_1_6', 'my_prevent_bad_dates', 10, 3);
function my_datepicker_prevent_bad_dates($options, $dpMinYear, $dpMaxYear, $element)
{
return "{
minDate: 0,
maxDate: new Date({$dpMaxYear}, 12 - 1, 31),
beforeShowDay: function (date) {
if (quformDisabledDates) {
for (var i = 0; i < quformDisabledDates.length; i++) {
var parts = quformDisabledDates[i].split('-');
if (date.getFullYear() == parts[0] && (date.getMonth()+1) == parts[1] && date.getDate() == parts[2]) {
return [false];
}
}
}
return [true];
}
}";
}
add_filter('iphorm_datepicker_options_iphorm_1_6', 'my_datepicker_prevent_bad_dates', 10, 4);
function my_print_dates_to_disable()
{
?>
<script type="text/javascript">
var quformDisabledDates = <?php echo json_encode(my_get_dates_to_disable()); ?>;
</script>
<?php
}
add_action('wp_head', 'my_print_dates_to_disable');

Related

Timer not binding DOM value in AngularJS

I'm a backend developer, who's trying hard to make a timer by comparing two different date formats. This part of the script is working great, but whenever I try to make recursive call, nothing is binding.
I almost tried everything, from passing it into a function, using the $interval, the setInterval, and on and on. The main reason is I cannot get the value of its loop, and binding into my DOM.
Here is some of my code. Here I set all variables for the countDown() function.
$scope.timer.list = {};
$scope.timer.date = new Date();
$scope.timer.list.D = '00';
$scope.timer.list.M = '00';
$scope.timer.list.Y = '00';
$scope.timer.list.h = '00';
$scope.timer.list.m = '00';
$scope.timer.list.s = '00';
$scope.begin = {};
$scope.begin.date = {};
$scope.begin.timer = {};
$scope.counter = {
show : false,
text : '00:00'
};
setInterval(function() {
$scope.obj = {
show : $scope.countDown($scope.privateshowcase.begin_at).show,
text : $scope.countDown($scope.privateshowcase.begin_at).text
}
$scope.counter = $scope.obj;
}, 1000);
Then, here is the function:
$scope.countDown = function(begin) {
$scope.timer.date = new Date();
$scope.timer.list.D = $filter('date')($scope.timer.date, 'dd');
$scope.timer.list.M = $filter('date')($scope.timer.date, 'MM');
$scope.timer.list.Y = $filter('date')($scope.timer.date, 'yyyy');
$scope.timer.list.h = $filter('date')($scope.timer.date, 'HH');
$scope.timer.list.m = $filter('date')($scope.timer.date, 'mm');
$scope.timer.list.s = $filter('date')($scope.timer.date, 'ss');
$scope.begin.full = begin.split(" ");
$scope.begin.date = $scope.begin.full[0].split("-");
$scope.begin.timer = $scope.begin.full[1].split(":");
$scope.begin.D = $scope.begin.date[2];
$scope.begin.M = $scope.begin.date[1];
$scope.begin.Y = $scope.begin.date[0];
$scope.begin.h = $scope.begin.timer[0];
$scope.begin.m = $scope.begin.timer[1];
$scope.begin.s = $scope.begin.timer[2];
if($scope.timer.list.Y == $scope.begin.Y) {
if($scope.timer.list.M == $scope.begin.M) {
if($scope.timer.list.D == $scope.begin.D) {
$scope.counter.diff_h = $scope.timer.list.h - $scope.begin.h;
if($scope.counter.diff_h == 0 || $scope.counter.diff_h == -1) {
if($scope.counter.diff_h == 0) {
if($scope.timer.list.m > $scope.begin.m) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if ($scope.timer.list.m <= $scope.begin.m) {
$scope.counter.show = true;
$scope.counter.diff_m = $scope.begin.m - $scope.timer.list.m;
if($scope.counter.diff_m <= 30) {
$scope.counter.diff_s = 60 - $scope.timer.list.s;
if($scope.counter.diff_s == 60) {
$scope.counter.s = "00";
$scope.counter.diff_m_f = $scope.counter.diff_m + 1;
} else if($scope.counter.diff_s >= 1 && $scope.counter.diff_s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
}
if($scope.counter.diff_m_f >= 1 && $scope.counter.diff_m_f <= 9) {
$scope.counter.m = "0" + $scope.counter.diff_m_f;
} else {
$scope.counter.m = $scope.counter.diff_m_f;
}
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else if ($scope.counter.diff_h == -1) {
$scope.counter.diff_timer = $scope.timer.m - 60;
$scope.counter.diff_m = $scope.begin.m - $scope.counter.diff_timer;
if($scope.counter.diff_m > 30) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if($scope.counter.diff_m <= 30) {
$scope.counter.show = true;
$scope.counter.diff_timer_s = $scope.timer.s - 60;
if($scope.counter.diff_timer_s == 60) {
$scope.counter.s = "00";
$scope.counter.m = $scope.counter.diff_m + 1;
} else if($scope.counter.s >= 1 && $scope.counter.s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
return $scope.counter = {
show : $scope.counter.show,
text : $scope.counter.text
};
}
'begin' is : 'YYYY/MM/DAY HH:MM:SS'
Maybe my way of thinking is not the good one, but at list I have a very functional timer, which replace every 1 to 9 into 01 to 09, convert the 60 into 00, can compare 2 different hours.
I think you are over complicating things a little bit. I came up with a simple countDown component made in angularjs 1.6.0 (it can be done with directives for angularjs older versions as well) that compares an input Date with the now Date.
You can play around with the input and change dates to see changes happen on the component, as long as you don't break the date format.
Note on dates: simple way to compare dates:
var date0 = new Date("2017-09-12T14:45:00.640Z");
var date1 = new Date("2017-09-13T14:45:00.640Z");
var dateDiff = new Date(date1.getTime() - date0.getTime());
// "1970-01-02T00:00:00.000Z"
Although dateDiff looks weird, it's basically one day from the zero date 1970-01-01T00:00:00.000Z.
Given that, you just let angularjs do the magic (or maybe trick).
{{ dateDiff | date:"d \'days\' hh:mm:ss" }}
Besides, if you don't want to work with dates in the natural form of javascript, you can use angularjs-moment which provide you date and time utility from momentjs regardless of javascript dates pitfalls.
Here is the working code:
angular
.module('app', [])
.run(function($rootScope) {
$rootScope.countDownToDate = new Date().addDays(2);
})
.component('countDown', {
template: '{{ $ctrl.timer | date:"d \'days\' hh:mm:ss" }}',
bindings: {
to: '<'
},
controller: function CountDownCtrl($interval) {
var $this = this;
this.$onInit = function() {
$interval($this.setTime, 1000);
};
$this.setTime = function() {
$this.timer = new Date(new Date($this.to).getTime() - new Date().getTime());
}
}
});
// bootstrap the app
angular.element(function() {
angular.bootstrap(document, ['app']);
});
// extension to add days on date
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div>
<center>
<h1>
<count-down to="countDownToDate" />
</h1>
<label for="countDownToDate">To Date</label>
<input type="datetime" name="countDownToDate" ng-model="countDownToDate">
</center>
</div>

Neon Chat js send message issue i don;t know how to implement php

I have this Js file and i want to implement Php request for sending message , history,update but nothing,i'm new with this, please help me.
The chat can be viewed here: http://demo.neontheme.com/extra/chat-api/
Db structure is: id | from | fromOpponent | message | time |unread
The js file:
var neonChat = neonChat || {
$current_user: null,
isOpen: false,
chat_history: [],
statuses: {
online: {class: 'is-online', order: 1, label: 'Online'},
offline: {class: 'is-offline', order: 4, label: 'Offline'},
idle: {class: 'is-idle', order: 3, label: 'Idle'},
busy: {class: 'is-busy', order: 2, label: 'Busy'}
}
};
;(function($, window, undefined)
{
"use strict";
var $chat = $("#chat"),
$chat_inner = $chat.find('.chat-inner'),
$chat_badge = $chat.find('.badge').add($('.chat-notifications-badge')),
$conversation_window = $chat.find(".chat-conversation"),
$conversation_header = $conversation_window.find(".conversation-header"),
$conversation_body = $conversation_window.find('.conversation-body'),
$textarea = $conversation_window.find('.chat-textarea textarea'),
sidebar_default_is_open = ! $(".page-container").hasClass('sidebar-collapsed');
$.extend(neonChat, {
init: function()
{
// Conversation Close
$conversation_window.on('click', '.conversation-close', neonChat.close);
$("body").on('click', '.chat-close', function(ev)
{
ev.preventDefault();
var animate = $(this).is('[data-animate]');
neonChat.hideChat(animate);
});
$("body").on('click', '.chat-open', function(ev)
{
ev.preventDefault();
var animate = $(this).is('[data-animate]');
neonChat.showChat(animate);
});
// Texarea
$textarea.keydown(function(e)
{
if(e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
neonChat.submitMessage();
return false;
}
else
if(e.keyCode == 27)
{
neonChat.close();
}
});
$chat.on('click', '.chat-group a', function(ev)
{
ev.preventDefault();
var $chat_user = $(this);
if($chat_user.hasClass('active'))
{
neonChat.close();
}
else
{
neonChat.open($chat_user);
}
});
$chat.find('.chat-group a').each(function(i, el)
{
var $this = $(el);
$this.append('<span class="badge badge-info is-hidden">0</span>');
});
neonChat.refreshUserIds();
neonChat.orderGroups();
neonChat.prefetchMessages();
neonChat.countUnreadMessages();
neonChat.puffUnreads();
// Chat
if($chat.hasClass('fixed') && $chat_inner.length && $.isFunction($.fn.niceScroll))
{
$chat.find('.chat-inner').niceScroll({
cursorcolor: '#454a54',
cursorborder: '1px solid #454a54',
railpadding: {right: 3},
railalign: 'right',
cursorborderradius: 1
});
}
// Chat Toggle
$("body").on('click', '[data-toggle="chat"]', function(ev)
{
ev.preventDefault();
var $this = $(this),
with_animation = $this.is('[data-animate]'),
collapse_sidebar = $this.is('[data-collapse-sidebar]');
neonChat.toggleChat(with_animation, collapse_sidebar);
});
},
updateConversationOffset: function($el)
{
var top_h = $conversation_window.find('.conversation-body').position().top + 1,
offset = $el.position().top - top_h,
minus = 0,
con_h = $conversation_window.height(),
win_h = $(window).height();
if($chat.hasClass('fixed') && offset + con_h > win_h)
{
minus = offset + con_h - win_h;
}
if($(".page-container.horizontal-menu").length)
{
minus += $(".page-container.horizontal-menu .navbar").height();
}
offset -= minus;
$conversation_window.transition({
top: offset,
opacity: 1
});
},
getChatHistoryLength: function()
{
var max_chat_history = parseInt($chat.data('max-chat-history'), 10);
if( ! max_chat_history || max_chat_history < 1)
{
max_chat_history = 25;
}
return max_chat_history;
},
submitMessage: function() // Submit whats on textarea
{
var msg = $.trim($textarea.val());
$textarea.val('');
if(this.isOpen && this.$current_user)
{
var id = this.$current_user.uniqueId().attr('id');
this.pushMessage(id, msg.replace( /<.*?>/g, '' ), $chat.data('current-user'), new Date());
this.renderMessages(id);
}
},
refreshUserIds: function()
{
$('#chat .chat-group a').each(function(i, el)
{
var $this = $(el),
$status = $this.find('.user-status');
$this.uniqueId();
var id = $this.attr('id');
if(typeof neonChat.chat_history[id] == 'undefined')
{
var status = $this.data('status');
if( ! status)
{
for(var i in neonChat.statuses)
{
if($status.hasClass(neonChat.statuses[i].class))
{
status = i;
break;
}
}
}
neonChat.chat_history[id] = {
$el: $this,
messages: [],
unreads: 0,
status: status
};
}
});
},
pushMessage: function(id, msg, from, time, fromOpponent, unread)
{
if(id && msg)
{
this.refreshUserIds();
var max_chat_history = this.getChatHistoryLength();
if(this.chat_history[id].messages.length >= max_chat_history)
{
this.chat_history[id].messages = this.chat_history[id].messages.reverse().slice(0, max_chat_history - 1).reverse();
}
this.chat_history[id].messages.push({
message: msg,
from: from,
time: time,
fromOpponent: fromOpponent,
unread: unread
});
if(unread)
{
this.puffUnreadsAll();
}
this.puffUnreads();
}
},
renderMessages: function(id, slient)
{
if(typeof this.chat_history[id] != 'undefined')
{
$conversation_body.html('');
for(var i in this.chat_history[id].messages)
{
var entry = this.chat_history[id].messages[i],
$entry = $('<li><span class="user"></span><p></p><span class="time"></span></li>'),
date = entry.time,
date_formated = date;
if(typeof date == 'object')
{
var hour = date.getHours(),
hour = (hour < 10 ? "0" : "") + hour,
min = date.getMinutes(),
min = (min < 10 ? "0" : "") + min,
sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
date_formated = hour + ':' + min;
}
// Populate message DOM
$entry.find('.user').html(entry.from);
$entry.find('p').html(entry.message.replace(/\n/g, '<br>'));
$entry.find('.time').html(date_formated);
if(entry.fromOpponent)
{
$entry.addClass('odd');
}
if(entry.unread && typeof slient == 'undefined')
{
$entry.addClass('unread');
entry.unread = false;
}
$conversation_body.append($entry);
}
this.updateScrollbars();
}
},
prefetchMessages: function()
{
$chat.find('.chat-group a').each(function(i, el)
{
var $contact = $(el),
id = $contact.attr('id'),
history_container = $contact.data('conversation-history');
if(history_container && history_container.length)
{
$($(history_container)).find('> li').each(function(j, el2)
{
var $entry = $(el2),
from = $entry.find('.user').html(),
message = $entry.find('p').html(),
time = $entry.find('.time').html(),
fromOpponent = $entry.hasClass('even') || $entry.hasClass('odd') || $entry.hasClass('opponent'),
unread = $entry.hasClass('unread');
neonChat.pushMessage(id, message, from, time, fromOpponent, unread)
});
}
});
},
// Set Cursor
$conversation_body.on('click', function()
{
$textarea.focus();
});
// Refresh Ids
neonChat.init();
})(jQuery, window);
What i have trying to implement but failed:
function sendChat(id, msg, from, time, fromOpponent, unread) {
$.ajax({
type: "POST",
url: "process.php",
data: {'function': 'from','message': message,'fromOpponent': id,'unread': unread},
dataType: "json",
success: function(data){
}
});
The Php/Html code:
<div id="chat" class="fixed" data-current-user="<?php echo $user->filter->username;?>" data-order-by-status="1" data-max-chat-history="25">
<?php
$conn = new PDO('mysql:host=localhost;dbname=testest', 'user', 'pass');
$sqlb = "SELECT * FROM `mls_users`";
$userz = $conn->query($sqlb);
foreach ($userz as $row) {
$name= $row['name'];
$surename = $row['surename'];
$status = $row['statusonline'];
$id = $row['id'];
echo "<a href='#' data-conversation-history='#sample_history_".$id."' id='$id'><span class='user-status is-".$status."line'></span> <em>$name $surename</em></a>";
}
?>
</div>
<!-- conversation template -->
<div class="chat-conversation">
<div class="conversation-header">
<i class="entypo-cancel"></i>
<span class="user-status"></span>
<span class="display-name"></span>
<small></small>
</div>
<ul class="conversation-body">
</ul>
<div class="chat-textarea">
<textarea class="form-control autogrow" placeholder="Type your message"></textarea>
</div>
</div>
</div>
<?php
$con = new PDO('mysql:host=localhost;dbname=chat', 'user', 'pass');
$sqlb = "SELECT * FROM `messages` ";
$userr = $con->query($sqlb);
foreach ($userr as $row) {
$from= $row['from'];
$fromOpponent = $row['fromOpponent'];
}
?>
<!-- Chat Histories -->
<?php
$conn = new PDO('mysql:host=localhost;dbname=chat', 'user', 'pass');
$sqlb = "SELECT TIME_FORMAT(time, '%H:%i') as `time`,`id`,`name`,`surename`,`message`,`unread`,`from`,`fromOpponent` FROM `message` WHERE `from`='$from' AND `fromOpponent`='$fromOpponent'";
$userz = $conn->query($sqlb);
foreach ($userz as $row) {
$id = $row['id'];
$from= $row['from'];
$fromOpponent= $row['fromOpponent'];
$name= $row['name'];
$surename= $row['surname'];
$message = $row['messagee'];
$time= $row['time'];
$unread = $row['unread'];
echo "<ul class='chat-history' id='sample_history_$from'>
<li class='opponent $unread'>
<span class='user'>$name $surename</span>
<p>$message</p>
<span class='time'>$time</span>";
}
?>
</li>
</ul>
</div>

How to allow datepicker to pick future dates in JQuery?

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/

FullCalendar recurring events array

I'm working on a recurring events backend for fullcalendar, and I've run into a strange problem.
My events are calculated on a page called events.php. The calendar is displayed on index.php and calls the events from events.php. My function on events.php outputs the correct string for the recurring events, but the calendar on index.php only displays the first event in each recurrence. However, if I copy the string that the array produces and paste it directly into the events.php page and comment out the render_fccalendar_events(); function and inthe end of events.php that produces the string, the calendar will display all of the recurring events correctly. From what I can see the output of the function, and what I'm pasting into the page are feeding the calendar on index.php exactly the same thing. Obviously there is some difference though because it's not rendering them the same. Any idea what in the world is going on here?
This is the events.php code:
<?php require_once('../../Connections/local_i.php');
require_once('../../webassist/mysqli/rsobj.php');
global $wpdb;
$wpdb = new WA_MySQLi_RS("wpdb",$local_i,0);
$wpdb->setQuery("SELECT wpdb.id, wpdb.location, wpdb.name, wpdb.description, wpdb.recurrence, wpdb.start_date, wpdb.end_date, wpdb.repeat, wpdb.repeat_desk, wpdb.occurrence, wpdb.occurrence_desk FROM wpdb");
$wpdb->execute();
ini_set('display_errors', '0');
function render_fccalendar_events() {
$_POST['start'] = (isset($_POST['start']) ? $_POST['start'] : strtotime('2014-09-01'));
$_POST['end'] = (isset($_POST['end']) ? $_POST['end'] : strtotime('2014-09-30'));
$start = date('Y-m-d',$_POST['start']);
$end = date('Y-m-d', $_POST['end']);
$readonly = (isset($_POST['readonly'])) ? true : false;
$events = fcdb_query_events($start, $end);
render_json(process_events($events, $start, $end, $readonly));
}
function process_events($events, $start, $end, $readonly) {
if ($events) {
$output = array();
foreach ($events as $event) {
$event->view_start = $start;
$event->view_end = $end;
$event = process_event($event, $readonly, true);
if (is_array($event)) {
foreach ($event as $repeat) {
array_push($output, $repeat);
}
} else {
array_push($output, $event);
}
}
return $output;
}
}
function process_event($input, $readonly = false, $queue = false) {
$output = array();
if ($repeats = generate_repeating_event($input)) {
foreach ($repeats as $repeat) {
array_push($output, generate_event($repeat));
}
} else {
array_push($output, generate_event($input));
}
if ($queue) {
return $output;
}
render_json($output);
}
function generate_event($input) {
$output = array(
'id' => $input->id,
'title' => $input->name,
'start' => $input->start_date,
'end' => $input->end_date,
'allDay' => ($input->allDay) ? true : false,
//'className' => "cat{$repeats}",
'editable' => true,
'repeat_i' => $input->repeat_int,
'repeat_f' => $input->repeat_freq,
'repeat_e' => $input->repeat_end
);
return $output;
}
function generate_repeating_event($event) {
$repeat_desk = json_decode($event->repeat_desk);
if ($event->repeat == "daily") {
$event->repeat_int =0;
$event->repeat_freq = $repeat_desk->every_day;
}
if ($event->repeat == "monthly") {
$event->repeat_int =2;
$event->repeat_freq = $repeat_desk->every_month;
}
if ($event->repeat == "weekly") {
$event->repeat_int =1;
$event->repeat_freq = $repeat_desk->every_week;
}
if ($event->repeat == "year") {
$event->repeat_int =3;
$event->repeat_freq = $repeat_desk->every_year;
}
if ($event->occurrence == "after-no-of-occurrences") {
if($event->repeat_int == 0){
$ext = "days";
}
if($event->repeat_int == 1){
$ext = "weeks";
}
if($event->repeat_int == 2){
$ext = "months";
}
if($event->repeat_int == 3){
$ext = "years";
}
$event->repeat_end = date('Y-m-d',strtotime("+" . $event->repeat_int . " ".$ext));
} else if ($event->occurrence == "no-end-date") {
$event->repeat_end = "2023-04-13";
} else if ($event->occurrence == "end-by-end-date") {
$event->repeat_end = $event->end_date;
}
if ($event->repeat_freq) {
$event_start = strtotime($event->start_date);
$event_end = strtotime($event->end_date);
$repeat_end = strtotime($event->repeat_end) + 86400;
$view_start = strtotime($event->view_start);
$view_end = strtotime($event->view_end);
$repeats = array();
while ($event_start < $repeat_end) {
if ($event_start >= $view_start && $event_start <= $view_end) {
$event = clone $event; // clone event details and override dates
$event->start_date = date('Y-m-d', $event_start);
$event->end_date = date('Y-m-d', $event_end);
array_push($repeats, $event);
}
$event_start = get_next_date($event_start, $event->repeat_freq, $event->repeat_int);
$event_end = get_next_date($event_end, $event->repeat_freq, $event->repeat_int);
}
return $repeats;
}
return false;
}
function get_next_date($date, $freq, $int) {
if ($int == 0)
return strtotime("+" . $freq . " days", $date);
if ($int == 1)
return strtotime("+" . $freq . " weeks", $date);
if ($int == 2)
return get_next_month($date, $freq);
if ($int == 3)
return get_next_year($date, $freq);
}
function get_next_month($date, $n = 1) {
$newDate = strtotime("+{$n} months", $date);
// adjustment for events that repeat on the 29th, 30th and 31st of a month
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 1 . " months", $date);
}
return $newDate;
}
function get_next_year($date, $n = 1) {
$newDate = strtotime("+{$n} years", $date);
// adjustment for events that repeat on february 29th
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 3 . " years", $date);
}
return $newDate;
}
function render_json($output) {
header("Content-Type: application/json");
echo json_encode(cleanse_output($output));
exit;
}
function cleanse_output($output) {
if (is_array($output)) {
array_walk_recursive($output, create_function('&$val', '$val = trim(stripslashes($val));'));
} else {
$output = stripslashes($output);
}
return $output;
}
function fcdb_query_events($start, $end) {
global $wpdb;
$result = array();
// $limit = ($limit) ? " LIMIT {$limit}" : "";
while(!$wpdb->atEnd()) {
$item = new stdClass;
$item->id = $wpdb->getColumnVal('id');
$item->location = $wpdb->getColumnVal('location');
$item->name = $wpdb->getColumnVal('name');
$item->description = $wpdb->getColumnVal('description');
$item->recurrence = $wpdb->getColumnVal('recurrence');
$item->start_date = $wpdb->getColumnVal('start_date');
$item->end_date = $wpdb->getColumnVal('end_date');
$item->repeat = $wpdb->getColumnVal('repeat');
$item->repeat_desk = $wpdb->getColumnVal('repeat_desk');
$item->occurrence = $wpdb->getColumnVal('occurrence');
$item->occurrence_desk = $wpdb->getColumnVal('occurrence_desk');
$item->allDay = false;
$result[] = $item;
$wpdb->moveNext();
}
$wpdb->moveFirst(); //return RS to first record
return return_result($result);
}
function return_result($result) {
if ($result === false) {
global $wpdb;
$this->log($wpdb->print_error());
return false;
}
return $result;
}
render_fccalendar_events();?>
This is the output of the events.php page
[{"id":"1","title":"test event","start":"2014-09-01","end":"2014-09-01","allDay":"","editable":"1","repeat_i":"1","repeat_f":"3","repeat_e":"2023-04-13"},{"id":"1","title":"test event","start":"2014-09-22","end":"2014-09-22","allDay":"","editable":"1","repeat_i":"1","repeat_f":"3","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-04","end":"2014-09-04","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-06","end":"2014-09-06","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-08","end":"2014-09-08","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-10","end":"2014-09-10","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-12","end":"2014-09-12","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-14","end":"2014-09-14","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-16","end":"2014-09-16","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-18","end":"2014-09-18","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-20","end":"2014-09-20","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-22","end":"2014-09-22","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-24","end":"2014-09-24","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-26","end":"2014-09-26","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"2","title":"test 2","start":"2014-09-28","end":"2014-09-28","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"},{"id":"3","title":"test 2","start":"2014-10-04 13:00:00","end":"2014-10-04 14:00:00","allDay":"","editable":"1","repeat_i":"0","repeat_f":"2","repeat_e":"2023-04-13"}]
This is the index.php code that's calling the events.php output:
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<?php echo date('Y-m-d'); ?>',
editable: true,
events: {
url: 'events.php',
type: 'POST'
},
error: function() {
alert('there was an error while fetching events!');
}
});
});
</script>
This seemed to work.
<?php require_once('../../Connections/local_i.php');
require_once('../../webassist/mysqli/rsobj.php');
global $wpdb;
$wpdb = new WA_MySQLi_RS("wpdb",$local_i,0);
$wpdb->setQuery("SELECT wpdb.id, wpdb.location, wpdb.name, wpdb.description, wpdb.recurrence, wpdb.start_date, wpdb.end_date, wpdb.repeat, wpdb.repeat_desk, wpdb.occurrence, wpdb.occurrence_desk, wpdb.repeat_key FROM wpdb");
$wpdb->execute();
ini_set('display_errors', '0');
function render_fccalendar_events() {
//$_POST['start'] = (isset($_POST['start']) ? strtotime($_POST['start']) : strtotime('2014-09-01'));
// $_POST['end'] = (isset($_POST['end']) ? strtotime($_POST['end']) : strtotime('2014-09-30'));
$_POST['start'] = strtotime($_POST['start']);
$_POST['end'] = strtotime($_POST['end']);
$start = date('Y-m-d',$_POST['start']);
$end = date('Y-m-d', $_POST['end']);
$readonly = (isset($_POST['readonly'])) ? true : false;
$events = fcdb_query_events($start, $end);
render_json(process_events($events, $start, $end, $readonly));
}
function process_events($events, $start, $end, $readonly) {
if ($events) {
$output = array();
foreach ($events as $event) {
$event->view_start = $start;
$event->view_end = $end;
$event = process_event($event, $readonly, true);
if (is_array($event)) {
foreach ($event as $repeat) {
array_push($output, $repeat);
}
} else {
array_push($output, $event);
}
}
return $output;
}
}
function process_event($input, $readonly = false, $queue = false) {
$output = array();
if ($repeats = generate_repeating_event($input)) {
foreach ($repeats as $repeat) {
array_push($output, generate_event($repeat));
}
} else {
array_push($output, generate_event($input));
}
if ($queue) {
return $output;
}
render_json($output);
}
function generate_event($input) {
$output = array(
'id' => $input->id,
'title' => $input->name,
'start' => $input->start_date,
'end' => $input->end_date,
'allDay' => ($input->allDay) ? true : false,
//'className' => "cat{$repeats}",
'editable' => true,
'repeat_i' => $input->repeat_int,
'repeat_f' => $input->repeat_freq,
'repeat_e' => $input->repeat_end
);
return $output;
}
function generate_repeating_event($event) {
$repeat_desk = json_decode($event->repeat_desk);
if ($event->repeat == "daily") {
$event->repeat_int =0;
$event->repeat_freq = $repeat_desk->every_day;
}
if ($event->repeat == "monthly") {
$event->repeat_int =2;
$event->repeat_freq = $repeat_desk->every_month;
}
if ($event->repeat == "weekly") {
$event->repeat_int =1;
$event->repeat_freq = $repeat_desk->every_week;
}
if ($event->repeat == "year") {
$event->repeat_int =3;
$event->repeat_freq = $repeat_desk->every_year;
}
if ($event->occurrence == "after-no-of-occurrences") {
if($event->repeat_int == 0){
$ext = "days";
}
if($event->repeat_int == 1){
$ext = "weeks";
}
if($event->repeat_int == 2){
$ext = "months";
}
if($event->repeat_int == 3){
$ext = "years";
}
$event->repeat_end = date('Y-m-d',strtotime("+" . $event->repeat_int . " ".$ext));
} else if ($event->occurrence == "no-end-date") {
$event->repeat_end = "2023-04-13";
} else if ($event->occurrence == "end-by-end-date") {
$event->repeat_end = $event->end_date;
}
if ($event->repeat_freq) {
// explode skipped events string (from database) into array $list_of_skipped_events
$event_start = strtotime($event->start_date);
$event_end = strtotime($event->end_date);
$repeat_end = strtotime($event->repeat_end) + 86400;
$view_start = strtotime($event->view_start);
$view_end = strtotime($event->view_end);
$repeats = array();
$counter = 1;
while ($event_start < $repeat_end) {
if ($event_start >= $view_start && $event_start <= $view_end) {
$event = clone $event; // clone event details and override dates
$event->start_date = date('Y-m-d', $event_start);
$event->end_date = date('Y-m-d', $event_end);
//if counter is in list of events to skip, don't do the next line
//if(! in_array($counter, $list_of_skipped_events))
array_push($repeats, $event);
}
$event_start = get_next_date($event_start, $event->repeat_freq, $event->repeat_int);
$event_end = get_next_date($event_end, $event->repeat_freq, $event->repeat_int);
$counter++;
}
return $repeats;
}
return false;
}
function get_next_date($date, $freq, $int) {
if ($int == 0)
return strtotime("+" . $freq . " days", $date);
if ($int == 1)
return strtotime("+" . $freq . " weeks", $date);
if ($int == 2)
return get_next_month($date, $freq);
if ($int == 3)
return get_next_year($date, $freq);
}
function get_next_month($date, $n = 1) {
$newDate = strtotime("+{$n} months", $date);
// adjustment for events that repeat on the 29th, 30th and 31st of a month
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 1 . " months", $date);
}
return $newDate;
}
function get_next_year($date, $n = 1) {
$newDate = strtotime("+{$n} years", $date);
// adjustment for events that repeat on february 29th
if (date('j', $date) !== (date('j', $newDate))) {
$newDate = strtotime("+" . $n + 3 . " years", $date);
}
return $newDate;
}
function render_json($output) {
header("Content-Type: application/json");
echo json_encode(cleanse_output($output));
exit;
}
function cleanse_output($output) {
if (is_array($output)) {
array_walk_recursive($output, create_function('&$val', '$val = trim(stripslashes($val));'));
} else {
$output = stripslashes($output);
}
return $output;
}
function fcdb_query_events($start, $end) {
global $wpdb;
$result = array();
// $limit = ($limit) ? " LIMIT {$limit}" : "";
while(!$wpdb->atEnd()) {
$item = new stdClass;
$item->id = $wpdb->getColumnVal('id');
$item->location = $wpdb->getColumnVal('location');
$item->name = $wpdb->getColumnVal('name');
$item->description = $wpdb->getColumnVal('description');
$item->recurrence = $wpdb->getColumnVal('recurrence');
$item->start_date = $wpdb->getColumnVal('start_date');
$item->end_date = $wpdb->getColumnVal('end_date');
$item->repeat = $wpdb->getColumnVal('repeat');
$item->repeat_desk = $wpdb->getColumnVal('repeat_desk');
$item->occurrence = $wpdb->getColumnVal('occurrence');
$item->occurrence_desk = $wpdb->getColumnVal('occurrence_desk');
$item->allDay = false;
$result[] = $item;
$wpdb->moveNext();
}
$wpdb->moveFirst(); //return RS to first record
return return_result($result);
}
function return_result($result) {
if ($result === false) {
global $wpdb;
$this->log($wpdb->print_error());
return false;
}
return $result;
}
render_fccalendar_events();?>
and
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<?php echo date('Y-m-d'); ?>',
editable: true,
events: {
url: 'events.php',
type: 'POST'
},
error: function() {
alert('there was an error while fetching events!');
}
});
});
</script>

How to pull selected date value from jsCalendar

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.

Categories