I have function that works with datepickers
Here it is
$(".multi_datepicker").each((key, elem) => {
$(elem)
.datepicker({
language: gon.locale,
minDate: new Date($(elem).attr("data-mindate")),
maxDate: new Date($(elem).attr("data-maxdate")),
autoClose: true,
onShow: (inst, animationCompleted) => {
if (animationCompleted) return true;
var id = Number(inst.$el.attr("id").split("_")[2]);
if (id < 0) return true;
var previous = $(`#search_legs_${id - 1}_date`);
if (previous.length == 0) return true;
var date = previous.datepicker().data("datepicker")
.selectedDates[0];
if (inst.selectedDates[0] < date) inst.selectedDates = [date];
inst.update("minDate", date);
},
onSelect: (dateText, inst) => {
var no_count = Number($("#search_no_legs").val());
var p = $("#search_legs_0_date").val();
for (let i = 1; i < no_count; i++) {
var leg_id = `#search_legs_${i}_date`;
if ($(leg_id).val() < p) $(leg_id).val(p);
p = $(leg_id).val();
}
}
})
.data("datepicker")
.selectDate(new Date($(elem).attr("data-defaultDate")));
});
}
But last row cause error
$(...).datepicker(...).data(...).selectDate is not a function
I cannot unserstood why?
How I can solve it?
Have you tried using .selectDate() after creating the date picker?
It would end up something like this:
$(elem).datepicker(..).data(..);
$(elem).selectDate(..);
Related
In our VS solution project, there are about 50 different JS files. What I am doing is moving the code out of these files (Require.js was used in these separated files) and combining all the code into one larger single JS file. Reason for this is to reduce the requests from the website.
Nonetheless, I am receiving 1 of 2 errors, depending on if I wrap the JS functions/prototypes w/ a self-containing function.
The code uses jQuery and jQuery.UI
First error (if wrapped) is FormBuilderDatePicker is not a constructor
Second error (if not wrapped) is this.registerSelectors is not a function
Calling JS code:
var quoteModuleObjArr = [
{ formId: "quote-module-form-moving", className: '.zipcode-moving', moveType: 'moving' },
{ formId: "quote-module-form-storage", className: '.zipcode-storage', moveType: 'storage' },
{ formId: "quote-module-form-moving-storage", className: '.zipcode-moving-storage', moveType: 'moving-storage' }
];
for (var i = 0; i < quoteModuleObjArr.length; i++) {
var formBuilder = null;
formBuilder = new FormBuilderDatePicker({
datepicker: '#' + quoteModuleObjArr[i].formId + ' input.isDatePicker',
formId: '#' + quoteModuleObjArr[i].formId
});
}
FormBuilderDatePicker function/prototype (wrapped):
var FormBuilderDatePicker = (function () { // remove for the 2nd error (unwrapped)
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents()
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M"
},
formId: ''
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate)
});
this.options.$datepicker.on("change", function () {
$(this).valid()
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
}
this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker; // remove for the 2nd error (unwrapped)
})(); // remove for the 2nd error (unwrapped)
I have also tried creating an init function, that calls FormBuilderDatePicker.registerSelectors() and FormBuilderDatePicker.delegateEvents(), and removed the last (2) lines within the constructor, but I get the same error, that registerSelectors() is not a function (same w/ delagateEvents().
I've also read that for prototypes to have the ability to be called, they need a return within the function. Hence, during testing, I added a return true; to the delegateEvents and registerSelectors functions, but this did not work either.
All code above is inside a $(function() {});
Updated Code/Solution:
setupFormBuilderDatePicker();
setupQuoteModuleDatePicker();
// ***********************************************
// Quote Module Date Picker
// ***********************************************
var FormBuilderDatePicker;
function setupFormBuilderDatePicker() {
FormBuilderDatePicker = (function () {
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents()
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M"
},
formId: ''
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate)
});
this.options.$datepicker.on("change", function () {
$(this).valid()
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
}
this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker;
})();
}
function setupQuoteModuleDatePicker() {
var quoteModuleObjArr = [
{ formId: "quote-module-form-moving", className: '.zipcode-moving', moveType: 'moving' },
{ formId: "quote-module-form-storage", className: '.zipcode-storage', moveType: 'storage' },
{ formId: "quote-module-form-moving-storage", className: '.zipcode-moving-storage', moveType: 'moving-storage' }
];
for (var i = 0; i < quoteModuleObjArr.length; i++) {
var formBuilder = null;
formBuilder = new FormBuilderDatePicker({
datepicker: '#' + quoteModuleObjArr[i].formId + ' input.isDatePicker',
formId: '#' + quoteModuleObjArr[i].formId
});
greyOutFacilityClosedDates(quoteModuleObjArr[i].formId, quoteModuleObjArr[i].className, formBuilder, quoteModuleObjArr[i].moveType);
//return formBuilder;
}
}
Just for testing purposes the OP's above posted code was taken as is ... results/conclusion ...
FormBuilderDatePicker exists as constructor function.
registerSelectors exists as prototypal method.
There was another error within the code of the prototypal delegateEvents methods though ... this.options.$datepicker.datepicker ... of cause is not provided with the current environment (settings).
The OP's script got sanitized and (re)formatted into the next provided example code in order to provide proof that the OP's code actually does work. Thus there must be some other reasons for the OP's script failures.
const dp = new FormBuilderDatePicker;
console.log({ registerSelectors: dp.registerSelectors });
console.log({ dp });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var FormBuilderDatePicker = (function () {
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents();
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M",
},
formId: '',
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate);
});
this.options.$datepicker.on("change", function () {
$(this).valid();
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
};
// this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker;
}());
</script>
I have a listeJNO variable that I need in beforeShowDay function
$('#calendrier').datepicker({
format: "dd/mm/yyyy",
weekStart: 1,
maxViewMode: 3,
language: "fr",
calendarWeeks: true,
beforeShowDay: function (date) {
for (var i = 0; i < listeJNO.length; i++) {
console.log(date >= listeJNO[i].Begin && date <= listeJNO[i].End);
if (date >= listeJNO[i].Begin && date <= listeJNO[i].End) {
return {
classes: 'morning-ferie'
};
}
}
}
but before, I need to define the listeJNO. I have a function which is doing this actually its getListeJNO(). So here's my problem, wherever I put the getListeJNO() to initialize data in listeJNO, the beforeShowDay option inside the $('calendrier').datepicker({...}) always goes first where listeJNO has no data inside
An option would be to initialize the datepicker when the load of listeJNO is completed.
You could do this by returning a promise and set the datepicker in the "then" callback.
First create the promise which loads the data into the listeJNO
var listeJNO;
var loadListeJNOpromise = new Promise(
function (resolve, reject) {
//load the data into listeJNO, then send it in the resolve callback
listeJNO = ....;
resolve('Load completed'); // fulfilled
//if something went wrong then reject it
//reject('Didnt work..');
}
);
Then consume the promise as this
//create a function thats sets the datepicker
var initializeDatepicker = function(){
$('#calendrier').datepicker({
format: "dd/mm/yyyy",
weekStart: 1,
maxViewMode: 3,
language: "fr",
calendarWeeks: true,
beforeShowDay: function (date) {
for (var i = 0; i < listeJNO.length; i++) {
console.log(date >= listeJNO[i].Begin && date <= listeJNO[i].End);
if (date >= listeJNO[i].Begin && date <= listeJNO[i].End) {
return {
classes: 'morning-ferie'
};
}
}
}
};
//declare a function which invokes the datepicker function in the promise
var initialize = function () {
loadListeJNOpromise
.then(function (fulfilled) {
console.log(fulfilled);
//call the datepicker initialize here
initializeDatepicker();
})
.catch(function (error) {
console.log(error);
});
};
//invoke the initilize
initialize();
Did you try and set the variable inside your beforeShowDay? I would think that would work. Have your listeJNO var declared outside the beforeShowDay function, and then set it inside that function. Something like this:
beforeShowDay: function (date) {
//Set your variable in this function
listeJNO = getListeJNO();
for (var i = 0; i < listeJNO.length; i++) {
console.log(date >= listeJNO[i].Begin && date <= listeJNO[i].End);
if (date >= listeJNO[i].Begin && date <= listeJNO[i].End) {
return {
classes: 'morning-ferie'
};
}
}
}
I ran into a deadly chaos on datepicker issues.
Who can solve my problem I can give 100 point as a return.
When I click the calendar on 2016-08-23 it will show me the 2016-08-22 as the date value.
Furthermore, the date value in angular model is also not correct.
I want to make the output can be consistent.
To reproduce the buggy issue, change your timezone between LA and TOKYO
DEMO site: https://test.jiyubi.com/tour_package/home
controller js
app.controller('tourPackageStartDatePickerCtrl',
function ($scope) {
$scope.initStartDate = function () {
$scope.startDate = $scope.startDate || null;
};
$scope.initStartDate();
$scope.dateOptions = {
baseDate: $scope.startDate,
minDate: $scope.startDate || moment.utc().toDate(),
};
$scope.openStartDateClick = function () {
$scope.startDatePopup.opened = true;
};
});
app.controller('tourPackageEndDatePickerCtrl',
function ($scope, $rootScope) {
$scope.clear = function () {
$scope.endDate = null;
};
$scope.endDateOptions = {
dateDisabled: disabledDays,
baseDate: new Date(),
};
$scope.openEndDateClick = function () {
$scope.endDatePopup.opened = true;
};
$scope.$watch("endDate", function (new_val, old_val) {
if (new_val && moment(new_val).isValid()) {
setTravelDateRange($scope.startDate, $scope.endDate);
}
}, true)
function setTravelDateRange(startDate, endDate) {
var start_date = moment_with_TAIPEI_TZ(startDate).format("YYYY/MM/DD");
var end_date = moment_with_TAIPEI_TZ(endDate).format("YYYY/MM/DD");
moment(startDate.toDateString()).tz("Asia/Taipei").format("YYYY/MM/DD");
$scope.q_param.startDate = start_date;
$scope.q_param.date_range = start_date + "-" + end_date;
}
});
helper.js
function moment_with_TAIPEI_TZ(time){
return moment(time).tz("Asia/Taipei");
}
function MOMENT_WITH_LOCAL(time){
return moment(time).local();
}
function discard_timezone(value) {
return moment.utc(value).format(DEFAULT_MOMENT_TIME_FORMAT);
}
function getYYYYMMDD(value) {
return moment.utc(value).format("YYYY/MM/DD");
}
function date_without_timezone(value) {
return moment.utc(value).toDate();
}
It's may be because of a timezone issue.
Could you please try to convert to date without considering the timezone?
this.convertToDateWithoutTimezone = function(date) {
if (date.toString().match(/(\d\d\d\d)-(\d\d)-(\d\d)/)) {
var year = $filter('date')(date.slice(0, 10), 'yyyy'),
month = $filter('date')(date.slice(0, 10), 'MM'),
day = $filter('date')(date.slice(0, 10), 'dd');
return new Date(year, month - 1, day);
} else {
return new Date(date);
}
};
I want my custom function be called instead of getfullyear() in java script how can I do this ? The point is to change a gregorian calendar to jallali in jomsocial.
for example when I write this
d=new Date(b.year,b.month,b.date+a);c.set("highlight",JalaliDate[d.getFullYear(),d.getMonth(),d.getDate()]
The result will be 2014/16/7, I want it to became 1393/6/25
This is the function that I want to be called
http://www.farsiweb.info/jalali/jalali.js
or
jQuery(function($){
$.datepicker.regional['fa'] = {
calendar: JalaliDate,
closeText: 'بستن',
prevText: 'قبل',
nextText: 'بعد',
currentText: 'امروز',
monthNames: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
monthNamesShort: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
dayNames: ['یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
dayNamesShort: ['یک', 'دو', 'سه', 'چهار', 'پنج', 'جمعه', 'شنبه'],
dayNamesMin: ['ی','د','س','چ','پ','ج','ش'],
weekHeader: 'ه',
dateFormat: 'dd/mm/yy',
firstDay: 6,
isRTL: true,
showMonthAfterYear: false,
yearSuffix: '',
calculateWeek: function(date) {
var checkDate = new JalaliDate(date.getFullYear(), date.getMonth(), date.getDate() + (date.getDay() || 7) - 3);
return Math.floor(Math.round((checkDate.getTime() - new JalaliDate(checkDate.getFullYear(), 0, 1).getTime()) / 86400000) / 7) + 1;
}};
$.datepicker.setDefaults($.datepicker.regional['fa']); });
function JalaliDate(p0, p1, p2) {
var gregorianDate;
var jalaliDate;
if (!isNaN(parseInt(p0)) && !isNaN(parseInt(p1)) && !isNaN(parseInt(p2))) {
var g = jalali_to_gregorian([parseInt(p0, 10), parseInt(p1, 10), parseInt(p2, 10)]);
setFullDate(new Date(g[0], g[1], g[2]));
} else {
setFullDate(p0);
}
function jalali_to_gregorian(d) {
var adjustDay = 0;
if(d[1]<0){
adjustDay = leap_persian(d[0]-1)? 30: 29;
d[1]++;
}
var gregorian = jd_to_gregorian(persian_to_jd(d[0], d[1] + 1, d[2])-adjustDay);
gregorian[1]--;
return gregorian;
}
function gregorian_to_jalali(d) {
var jalali = jd_to_persian(gregorian_to_jd(d[0], d[1] + 1, d[2]));
jalali[1]--;
return jalali;
}
function setFullDate(date) {
if (date && date.getGregorianDate) date = date.getGregorianDate();
gregorianDate = new Date(date);
gregorianDate.setHours(gregorianDate.getHours() > 12 ? gregorianDate.getHours() + 2 : 0)
if (!gregorianDate || gregorianDate == 'Invalid Date' || isNaN(gregorianDate || !gregorianDate.getDate())) {
gregorianDate = new Date();
}
jalaliDate = gregorian_to_jalali([
gregorianDate.getFullYear(),
gregorianDate.getMonth(),
gregorianDate.getDate()]);
return this;
}
this.getGregorianDate = function() { return gregorianDate; }
this.setFullDate = setFullDate;
this.setMonth = function(e) {
jalaliDate[1] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
}
this.setDate = function(e) {
jalaliDate[2] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
};
this.getFullYear = function() { return jalaliDate[0]; };
this.getMonth = function() { return jalaliDate[1]; };
this.getDate = function() { return jalaliDate[2]; };
this.toString = function() { return jalaliDate.join(',').toString(); };
this.getDay = function() { return gregorianDate.getDay(); };
this.getHours = function() { return gregorianDate.getHours(); };
this.getMinutes = function() { return gregorianDate.getMinutes(); };
this.getSeconds = function() { return gregorianDate.getSeconds(); };
this.getTime = function() { return gregorianDate.getTime(); };
this.getTimeZoneOffset = function() { return gregorianDate.getTimeZoneOffset(); };
this.getYear = function() { return jalaliDate[0] % 100; };
this.setHours = function(e) { gregorianDate.setHours(e) };
this.setMinutes = function(e) { gregorianDate.setMinutes(e) };
this.setSeconds = function(e) { gregorianDate.setSeconds(e) };
this.setMilliseconds = function(e) { gregorianDate.setMilliseconds(e) }; }
Thanks
If you are using http://www.farsiweb.info/jalali/jalali.js, try
function printJalali(year, month, day) {
var jalali = gregorian_to_jalali([year, month+1, day]);
return jalali[0] + "/" + jalali[1] + "/" + jalali[2];
}
var today = new Date();
alert(printJalali(today.getFullYear(), today.getMonth(), today.getDate()));
I'm trying to disable certain dates from a Jquery UI datepicker calendar.
My problem is that only the last date checked by disableDays function is disabled, not all of them. Why it disables only the last checked date. Should I return a different response from this function ?
Full script:
var disabled_days = new Array(); // Array of Date() objects
$('.date-picker-day').live('click', function () {
$(this).datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'dd',
beforeShow: function () {
[..]
},
beforeShowDay: disableDays,
onClose: function (dateText, inst) {
}
}).focus();
});
function disableDays(date) {
var ret = false;
$.each(disabled_days, function (k, v) {
if (v.getDate() == date.getDate()) {
console.log(v + 'vs.' + date + ' invalid');
ret = [false];
} else {
ret = [true];
}
});
return ret;
}
You need to stop further iterations of the disabled_days array as soon as a negative match is found, else in the next value iteration the date will not match and ret will again get true value
function disableDays(date) {
var ret = false;
$.each(disabled_days, function (k, v) {
if (v.getDate() == date.getDate()) {
console.log(v + 'vs.' + date + ' invalid');
ret = [false];
return false;
} else {
ret = [true];
}
});
return ret;
}
Demo: Fiddle