eventRender not rendering nor displaying events on fullcalendar - javascript

Good day, i'm using fullcalendar plugin to show events on my calendar. right now i'm having a problem on displaying the events in my calendar. i am using json result to get the data that will show on my calendar..
here's my code
Controller:
[DontWrapResult]
public JsonResult GetCalendarEvents(string start, string end)
{
var fromDate = Convert.ToDateTime(start);
var toDate = Convert.ToDateTime(end);
var result = _utils.GetEventsCalendar("ALL", fromDate, toDate);
var eventList = from item in result
select new
{
id = item.CalendarId.ToString(),
title = item.Title,
description = item.Description,
start = item.FromDate.ToLocalTime().ToString("s"),
end = item.EndDate.HasValue ? item.EndDate.Value.ToLocalTime().ToString("s") : item.FromDate.ToLocalTime().ToString("s"),
NoofGuests = item.NoofGuests,
allDay = item.AllDay,
type = item.CalType,
requestedBy = item.RequestedBy,
driverName = item.DriverName,
providerName = item.ProviderName,
phoneNo = item.PhoneNo,
controlNumber = item.ControlNumber,
status =item.StatusId
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
then in my javascript:
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
droppable: false, // this allows things to be dropped onto the calendar
events: '#Url.Action("GetCalendarEvents/")',
eventRender: function (event, element) {
element.attr('href', 'javascript:void(0);');
if (event.start <date && event.end <date) {
element.css('background-color', '#ed5565');
element.css('border', '1px solid #ed5565');
} else if (event.start <=date && event.end >= date) {
element.css('background-color', '#f8ac59');
element.css('border', '1px solid #f8ac59');
}
if (event.status == 1) {
element.css('background-color', '#0000FF');
element.css('border', '1px solid #0000FF');
} else if (event.status == 4)
{
element.css('background-color', '#00CC33');
element.css('border', '1px solid #00CC33');
}
element.click(function () {
if (event.type == 'Event') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Events")?id=' + event.id;
}
else if (event.type == 'ApproveBook') {
$('#forBook').show();
$('#permitdetails').hide();
$('#delPer').show();
$("#NoofGuests").html(event.NoofGuests);
}
else {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Announcements")?id=' + event.id;
}
if (event.type == 'DeliveryPermit') {
$('#delPer').hide();
$('#permitdetails').show();
$("#controlNo").html(event.controlNumber);
$("#requestby").html(event.requestedBy);
$("#deliverydate").html(moment(event.start).format('MMM Do'));
$("#contractor").html(event.providerName);
$("#contact").html(event.phoneNo);
$("#drivername").html(event.driverName);
if (event.status == 1) { $("#status").html("Arrived"); }
else if (event.status == 4) { $("#status").html("Completed"); }
else { $("#status").html("Submitted"); }
//getDetails(event.id);
var urls = '#Url.Action("Calendarpermit", "AdminHome")?id=' + event.id + '&strHide=' + "strHide";
var url = '#Url.Action("Edit", "DeliveryPermits",new { area = "Permit" })/' + event.id
$.ajax({
url: urls,
cache: false,
data: {id : event.id},
contentType: 'application/html; charset=utf-8',
type: "POST",
dataType: "html",
success: function (data){
$('#permitItem').html(data);
}
});
}
if (event.type == 'Announcement') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
$("#startTime").html(moment(event.start).format('MMM Do '));
$("#endTime").html(moment(event.start).format('MMM Do'));
} else {
$("#startTime").html(moment(event.start).format('MMM Do h:mm A'));
$("#endTime").html(moment(event.end).format('MMM Do h:mm A'));
}
$("#eventInfo").html(event.description);
$("#eventLink").attr('href', url);
$("#eventContent").dialog({
modal: true, title: event.title, width: 350
});
});
}
});
i tried to put an alert inside the eventRender but it didn't pass or show data in my calendar.. what i am doing wrong? thanks in advance

Related

Lazy loading works for loading data, but not when filtering

Here the first script is written for lazy loading the table data and the second script is written for filtering with lazy loading but the second one is not working.
I have a Codeigniter report in which I did some filtering on the table data. I am using jQuery AJAX to lazy load data. What I expected is that when I fetch the data with a filter the lazy loading is not working. Shall i use first script for both table load by default and for filter. i am getting confusion. Can anyone please tell me how to merge both script as a single script for both. Please help.
$(document).ready(function() {
$('#filter').popover({
placement: 'bottom',
title: (' ') + '<button type="button" class="close pull-right" data-dismiss="alert" style="color:black;">×</button>',
html: true,
content: $('#customdiv').html()
});
$(document).on("click", ".popover .close", function() {
$(this).parents(".popover").popover('hide');
});
var limit = 20;
var start = 0;
var action = 'inactive';
function lazzy_loader(limit) {
var output = '';
for (var count = 0; count < limit; count++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_message').html(output);
}
lazzy_loader(limit);
function search_fields(limit, start) {
$(".spinner").show();
$.ajax({
url: "<?=base_url()?>missed_call_campaign/fetch_data",
method: "POST",
data: {
limit: limit,
start: start
},
cache: false,
success: function(data) {
$(".spinner").hide();
if (data == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found</p>');
action = 'active';
} else {
$('#load_data').append(data);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
if (action == 'inactive') {
action = 'active';
search_fields(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive') {
lazzy_loader(limit);
action = 'active';
start = start + limit;
setTimeout(function() {
search_fields(limit, start);
}, 100);
}
});
});
function subcategory() {
var ClickedCategory = new Array();
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subcategory_checkbox",
data: {
type: 'text',
ClickedCategory: ClickedCategory
},
success: function(response) {
$("#collapsepp").hide();
$("#collapseqq").html(response);
}
});
}
function subsource() {
var ClickedSource = new Array();
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subsource_checkbox",
data: {
type: 'text',
ClickedSource: ClickedSource
},
success: function(response) {
$("#collapserr").hide();
$("#collapsess").html(response);
}
});
}
function clearFilter() {
location.reload();
}
$(document).ready(function() {
$(document).on("click", "#data_filter", function() {
var CheckedRep = new Array();
var ClickedStatus = new Array();
var ClickedType = new Array();
var ClickedCategory = new Array();
var ClickedSubCategory = new Array();
var ClickedSubCategory_Filter = new Array();
var ClickedSource = new Array();
var ClickedSubSource = new Array();
var ClickedSubSource_Filter = new Array();
$('.RepClicked').each(function() {
if ($(this).is(':checked')) {
CheckedRep.push($(this).val());
}
});
$('.StatusClicked').each(function() {
if ($(this).is(':checked')) {
ClickedStatus.push($(this).val());
}
});
$('.TypeClicked').each(function() {
if ($(this).is(':checked')) {
ClickedType.push($(this).val());
}
});
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$('.SubSourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource.push($(this).val());
}
});
$('.SubCategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory.push($(this).val());
}
});
$('.SubCategoryChecked_Filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory_Filter.push($(this).val());
}
});
$('.SubSourceClicked_filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource_Filter.push($(this).val());
}
});
if ((CheckedRep.length > 0) || (ClickedStatus.length > 0) || (ClickedType.length > 0) || (ClickedCategory.length > 0)
(ClickedSource.length > 0) || (ClickedSubSource.length > 0) || (ClickedSubCategory.length > 0) ||
(ClickedSubCategory_Filter.length > 0) || (ClickedSubSource_Filter.length > 0)) {
var limits = 20;
var starts = 0;
var actions = 'inactive';
lazzy_loading(limits);
if (actions == 'inactive') {
actions = 'active';
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data_filter").height() && actions == 'inactive') {
lazzy_loading(limits);
actions = 'active';
starts = starts + limits;
setTimeout(function() {
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}, 100);
}
});
}
});
function lazzy_loading(limits) {
var output = '';
for (var counts = 0; counts < limits; counts++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_filter').html(output);
}
function filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter) {
$.ajax({
url: "<?=base_url()?>missed_call_campaign/toDoAjax",
method: "POST",
data: {
type: 'text',
CheckedRep: CheckedRep,
ClickedStatus: ClickedStatus,
ClickedType: ClickedType,
ClickedCategory: ClickedCategory,
ClickedSource: ClickedSource,
ClickedSubSource: ClickedSubSource,
ClickedSubCategory: ClickedSubCategory,
ClickedSubCategory_Filter: ClickedSubCategory_Filter,
ClickedSubSource_Filter: ClickedSubSource_Filter,
limits: limits,
starts: starts
},
cache: false,
success: function(response) {
$(".spinner").hide();
$("#load_data").hide();
if (response == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found123</p>');
action = 'active';
} else {
$('#load_data_filter').append(response);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
});
I suggest you to reinitialize the lazy load after success you fetched data from the back end.

Full calendar updateEvent. Cannot read property 'clone' of undefined

I'm using FullCalendar and trying to update an event with a modal. When I try to update the event, I'm getting the cannot read property 'clone' of undefined.
I'm using the clientEvents method, as stated in their documentation
event must be the original Event Object for an event, not merely a reconstructed object. The original Event Object can obtained by callbacks such as eventClick, or by the clientEvents method.
to get my original event, however, when I submit I still get this error.
Here's my code:
initializeFullCalendar: function () {
var loc = $('#locationCodes').val();
$('.autocomplete').keypress(function (key) {
if (key.charCode == 32 && $('.autocomplete').val().length >= 1) { return true };
// if (key.charCode == 92 || key.charCode == 47 || key.charCode < 65) return false;
});
$(document).tooltip({
track: true,
hide: { effect: "explode", duration: 300 }
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
selectable: true,
selectHelper: true,
dayclick: function(date){
},
select: function (date, start, end) {
if ($('#job').attr('class') === 'XXX') {
EMP.calendarPopup(date, start, end);
}
},
eventSources: [
{
url: '/Home/getAllEvents/',
data: { Locations: loc },
type: 'POST'
}
],
eventClick: function (event, element, date) {
EMP.editCalendarPopup(date, event);
},
height: 350,
defaultView: 'basicWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventRender: function (data, element) {
var start = moment(data.start._i).format('LT');
var end = moment(data.end._i).format('LT');
}
});
},
editCalendarPopup: function (date, event) {
$('.calendar-popup').addClass('active edit');
var event_date = event.start._i.split("T")[0];
var start = event.start._i.split("T")[1]
var end = event.end._i.split("T")[1];
start = EMP.convert12hr(start);
end = EMP.convert12hr(end);
var startTime = start.split(' ')[0];
var startMod = start.split(' ')[1];
var endTime = end.split(' ')[0];
var endMod = end.split(' ')[1];
$('#date').val(event_date);
$('#calendar-event').val(event.title);
$('#calendar-custodian').val(event.cust);
$('#calendar-start').val(startTime);
$('#startampm').val(startMod)
$('#calendar-end').val(endTime);
$('#endampm').val(endMod);
$('#hiddenEvent').val(event.title);
$('#hiddenCustodian').val(event.cust);
$('#hiddenStart').val(event.start._i);
$('#hiddenEnd').val(event.end._i);
$('#hiddenId').val(event._id);
},
editCalendarAjax: function() {
var event = $("#calendar").fullCalendar('clientEvents');
var hiddenId = $('#hiddenId').val();
event = $.grep(event, function(e){return e._id === hiddenId});
event = event[0];
var event_date = $('#date').val();
var title = $('#calendar-event').val();
var cust = $('#calendar-custodian').val();
var start = $('#calendar-start option:selected').val();
var end = $('#calendar-end option:selected').val();
var startampm = $("#startampm option:selected").val();
var endampm = $("#endampm option:selected").val();
start = start + " " + startampm;
end = end + " " + endampm;
start = EMP.convert24hr(start);
end = EMP.convert24hr(end);
var locCode = $('.location').attr('id');
var date_start = event_date + "T" + start;
var date_end = event_date + "T" + end;
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
var origEvent = $('#hiddenEvent').val();
var origCust = $('#hiddenCustodian').val();
var origStart = $('#hiddenStart').val();
var origEnd = $('#hiddenEnd').val();
item = {};
item["title"] = title;
item["cust"] = cust;
item["start"] = date_start;
item["end"] = date_end;
item["locCode"] = locCode;
item["origEvent"] = origEvent;
item["origCust"] = origCust;
item["origStart"] = origStart;
item["origEnd"] = origEnd;
$.ajax({
type: "POST",
url: "/Home/updateCalendar",
data: item,
success: function () {
console.log('success!');
},
error: function (xhr, ajaxOptions, thrownError) {
window.alert("Please click here to refresh your session");
console.log('error')
}
});
$('#calendar').fullCalendar('unselect');
EMP.togglePopups();
},
The issue was I was using an old version of FullCalendar. After updating I stopped getting the error.
One more thing I had to change was this:
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
to this:
if (title) {
event.title = title;
event.start = date_start;
event.cust = cust;
event.end = date_end;
$('#calendar').fullCalendar('updateEvent', event); // stick? = true
}
because I was overwriting my event. Everything works now.

press confirm button before save

I'm having a problem with the way I save information in ajax with alert, I made it using confirm in JQuery but the button text can't be changed I so decided to make my own dialog box so I can modify the buttons, but the problem is the data saves before I click the save button.
function saveEdit(e) {
var result = '';
var item = $('input[name=username]').val();
$.ajax({
url: root + 'ccards/getAllDetails',
data: {
item: item
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hour = dateObj.getUTCHours()
var minute = dateObj.getUTCMinutes();
var second = dateObj.getUTCSeconds();
var datetoday = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
var selected_date = Date.parse(data.modified);
var today = Date.parse(datetoday);
var d = new Date(data.modified);
var h = d.getHours();
var m = d.getMinutes();
var username = data.username.toUpperCase();
var coreuser = data.core_user.username.toUpperCase();
var hr = '';
var time = '';
if (h <= '12') {
hr = h;
time = hr + ":" + m + " AM";
} else {
hr = h - 12;
time = hr + ":" + m + " PM";
}
if (Math.abs(today - selected_date) <= 60 * 60 * 24 * 1000) {
$('#confirmSave').show().dialog({
height: 200,
width: 500,
zIndex: 10,
modal: true,
resizable: false
});
$('#time').html(time);
$('#coreuser').html(coreuser);
if ($('#confirmSave button[name=submit]').data('clicked')) {
result = true;
} else if ($('#confirmSave button[name=cancel]').data('clicked')) {
result = false;
}
}
}
});
return result;
}
$('.clientForm').submit(function(event) {
var form = this;
console.log(form);
if ($("input[name='action']", form).val() == 'save' || $("input[name='action']", form).val() == 'savenew' || $("input[name='action']", form).val() == 'login') {
if ((!validate_email(form)) || (!validate(form))) {
mode = 'edit';
setMode(mode);
return false;
}
}
var save = saveEdit();
if (save == true) {
var dt = $(this).serializeArray();
var action = root + $("input[name='module']", form).val() + $("input[name='method']", form).val();
$('.fields', this).slideUp('fast');
$('.response', this).html("<div class='load'>Processing, please wait...</div>");
$.ajax({
type: 'POST',
url: action,
data: dt,
dataType: 'json',
success: function(data) {
if (data) procJSON.init(data, form);
},
complete: function(data) {
},
error: function(data) {
onError(data);
}
});
}
return false;
});
I recently used the noty plugin, alongside jQuery's deferred to solve a similar problem.
First, a function to show the confirm dialog and return a promise-like object, which resolves to true if the Ok button is pressed, or false if the Cancel button is pressed.
function showConfirm(msg) {
var dfd = $.Deferred();
noty({
text: msg,
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme',
modal: true,
buttons:
[{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: $noty => {
$noty.close();
dfd.resolve(true);
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: $noty => {
$noty.close();
dfd.resolve(false);
}
}]
});
return dfd.promise();
}
Then you can do something like...
$('.clientForm').submit(function(event) {
showConfirm("Do you wish to save?").then(function(confirmed) {
if (!confirmed) {
return;
}
// make ajax request here
}
}

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/

Accept pre-populated form field input

I just set up my date-picker to auto populate it's input field with today's date.
Normally, a user would have to select their own date and submit their selection via the enter key or, I think in my case, any key would do it.
Is there anyway to automatically do this? Since the field is pre-populated, I want the results for today's date to appear automatically on page load, without the user needing to accept the date(today) that has been pre-populated into the field.
Here's my code if it's helpful:
<script>
function displayResult() {
var k;
if (window.event) // IE8 and earlier
{
k = event.keyCode;
} else if (event.which) // IE9/Firefox/Chrome/Opera/Safari
{
k = event.which;
}
if (k == 13) //13 = 'Enter' key
{
var dt = $("#datepicker").val();
//alert(dt);
if (dt != '') {
$.ajax({
type: "POST",
url: "search_date.php",
data: "dt=" + dt,
success: function (option) {
$("#results").html(option).listview("refresh");
}
});
} else {
$("#results").html("");
}
return false;
}
}
</script>
<script type="text/javascript">
$(function () {
$("#datepicker").datepicker();
$("#datepicker").datepicker("setDate", new Date());
$('#datepicker').datepicker({
inline: true,
showOn: "button",
buttonImage: "images/calendar.gif",
showAnim: "slideDown",
changeMonth: true,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function (dateText, inst) {
//alert($('#datepicker').datepicker( "getDate" ))
//alert("dateText: " + dateText + ", inst: " + inst);
var dt = dateText;
if (dt != '') {
$.ajax({
type: "POST",
url: "search_date.php",
data: "dt=" + dt,
success: function (option) {
$("#results").html(option).listview("refresh");
}
});
} else {
$("#results").html("");
}
return false;
}
});
$('body').ready(function(){
var dt = $("#datepicker").val();
//alert(dt);
if(dt != '')
{
$.ajax
({
type: "POST",
url: "search_date.php",
data: "dt="+ dt,
success: function(option)
{
$("#results").html(option).listview("refresh");
}
});
}
else
{
$("#results").html("");
}
return false;
});
</script>
$('body').ready(function(){
var dt = $("#datepicker").val();
//alert(dt);
if(dt != '')
{
$.ajax
({
type: "POST",
url: "search_date.php",
data: "dt="+ dt,
success: function(option)
{
$("#results").html(option).listview("refresh");
}
});
}
else
{
$("#results").html("");
}
return false;
});

Categories