disable jQuery DatePicker dates - javascript

I have attempted to enable selection of only the first date of each month in a jQuery datepicker. The possible dates are listed in var enabledates.
var enabledDays = ["6-1-2013", "7-1-2013", "8-1-2013",
"9-1-2013", "10-1-2013", "11-1-2013"];
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y, enabledDays) != -1
|| new Date() > date) {
return [true];
}
}
return [false];
}
$(function(){
$.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));
$("#datepicker1, #datepicker2, #datepicker3").datepicker({
dateFormat: "yy-mm-dd",
duration: "normal",
numberOfMonths: [ 1, 2 ],
constrainInput: true,
beforeShowDay: nationalDays
});
});
How can I apply this first date constraint to the whole calendar?

If you just want to enable a range I would say you can use the Option properties minDate an maxDate.
Regarding your Problem to enable all Dates from an array. Please have a look at this fiddle http://jsfiddle.net/uYe9X/
function available(date) {
var dt= date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if (availableDates.indexOf(dt) !== -1) {
return [true, "","available"];
} else {
return [false,"","not available"];
}
}
As Pedro mentioned you could use the beforeShowDay Callback to reference a function which computes if the day should be enabled. The callback is used for every day which is displayed in the datepicker.
http://api.jqueryui.com/datepicker/#option-beforeShowDay

Related

JS Datepicker: Disable past dates + specific days of the week + specific dates

I have a datepicker in JS where I disabled passed dates AND only allow saturdays like this:
$(document).ready(function(){
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: function(date){
var day = date.getDay();
return [day == 6];
}});
});
I also have a code that lets me disable specific dates like this:
/** Days to be disabled as an array */
var disableddates = ["26-05-2018"];
function DisableSpecificDates(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the mm-dd-yyyy format
// Take note that we will increment the month count by 1
var currentdate = (m + 1) + '-' + d + '-' + y ;
// We will now check if the date belongs to disableddates array
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if ($.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
}
With adding this, it works:
beforeShowDay: DisableSpecificDates
The issue I have is that i can't make both work. I'm not sure How can disable the past dates and all days except saturdays AND also disable specific given dates in the array, while seperatly they do work. I always get syntax errors when trying for example:
beforeShowDay: DisableSpecificDates, function(date){
var day = date.getDay();
return [day == 6];
}});
Is this possible to do?
Yes, it's possible to achieve this. You want to create one function and return [false] from it if:
date is a Saturday or
date is contained within disableddates array
Here's the example:
var disableddates = ["26-04-2018"];
function DisableDates(date) {
var selectable = !isSaturday(date) && !isDateDisabled(date);
return [selectable];
}
function isSaturday(date) {
var day = date.getDay();
return day === 6;
}
function isDateDisabled(date) {
var m = date.getMonth() + 1;
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the dd-mm-yyyy format
if(d < 10) d = '0' + d;
if(m < 10) m = '0' + m;
var currentdate = d + '-' + m + '-' + y;
// Check if disableddates array contains the currentdate
return disableddates.indexOf(currentdate) >= 0;
}
And then just pass DisableDates function as the value of your beforeShowDay option:
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: DisableDates
});

jquery datepicker disable and also custom css

i would like have a certain dates in my jquery to be disabled or perhaps unclickable but with a different class. So far what i got is this which only disables the date but i can't seem to add a class to it.
var unavailableDates = ["9-7-2016"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
var dateToday = new Date();
$("#iDate").multiDatesPicker({
defaultDate: new Date(),
dateFormat: 'dd MM yy',
beforeShowDay: unavailable,
minDate: dateToday
});
I found this while doing some searching which is very close to what i want
http://jsfiddle.net/ambiguous/pjJGf/
but i don't know how to make it so that it calls the dates instead of fixed day of the month.
The beforeShowDay function must return an array with two elements (an an optional third). The second array element is the name of the class you want to return for a day. So modify the return statement in the else part of your if condition to return [false, "name-of-css-class", "Unavailable"];

6Jquery datepicker date blocking not working?

I have written code to block past dates and dates in the unavilabledates array, but only the second element of the array is blocked, rest are available for selection. Any idea how to figure it out?
var unavailableDates = ["6-3-2016", "5-28-2016", "5-27-2016", "6-28-2016"];
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender:function(date){
dmy = (date.getMonth() + 1) + "-" +date.getDate() + "-" + date.getFullYear();
return (date.valueOf() < now.valueOf() || ($.inArray(dmy, unavailableDates) == 1))?'disabled':'';
}
}
Output:// 5-28-2016 blocked , rest are not
I presume you use the jQuery UI Datepicker, use the beforeShowDay function instead of the onRender:
var unavailableDates = ["2016-03-06"]; // Dates formatted the same way as the beforeShowDay formatDate() function requires it
$('#dpd1').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ unavailableDates.indexOf(string) == -1 ]
},
minDate: 0
});
EDIT
I found the error, the formatDate('yy-mm-dd') in the beforeShowDay function checks for a 2016-05-25 date, while your provided array has dates like 6-3-2016. This is way the dates are not disabled.
See the updated code and a jsfiddle to go with it: https://jsfiddle.net/orttL83d/ (In this example I disabled 26th of May and all past dates)

Disable/Enable selected date range on jQuery datepicker UI

So I have the following demo http://dev.driz.co.uk/week.html that shows a jQuery UI datepicker that has multiple instances for each month of the year.
I've modified it so that the user selects entire weeks and then start and end dates for those weeks are stored on the right hand sidebar with a week number.
What I want to do is disable the dates once the user has selected them so they can see on the calender picker what dates have been selected (and also prevent them from adding the same date range more than once).
However I don't know where to start with this... I've created some enable and disable date functions but don't know how to actually disable the dates using the beforeShowDay method.
For example:
var array = ["2013-03-14","2013-03-15","2013-03-16"]
$('.week-picker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
But how would I disable a range of dates? As I only have the start and end dates. And can I call the beforeShowDay AFTER the datepicker is on the page like in my example? AND how can I then re-enable the dates?
Here's the code:
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active');
}, 1);
}
$('.week-picker').datepicker( {
defaultDate: '01/01/2014',
minDate: '01/01/2013',
maxDate: '01/01/2015',
changeMonth: false,
changeYear: true,
showWeek: true,
showOtherMonths: true,
selectOtherMonths: true,
numberOfMonths: 12,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
addWeek($.datepicker.iso8601Week(new Date(dateText)), $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
disableDates( $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
$('.remove').live('click', function(e){
enableDates($(this).attr('data-startdate'), $(this).attr('data-enddate'));
$(this).parent('div').remove();
});
});
// adds the week to the sidebar
function addWeek(weekNum, startDate, endDate){
$('.weeks-chosen').append('<div data-startdate="'+startDate+'" data-enddate="'+endDate+'"><span class="weekNum">Week '+ (weekNum - 1) +'</span> - <span class="startDate">'+startDate+'</span> - <span class="endDate">'+endDate+'</span> | <span class="remove">X Remove</span></div>');
}
// disable the dates on the calendar
function disableDates(startDate, endDate){
}
// enable the dates on the calendar
function enableDates(startDate, endDate){
}
In short there are two questions here... How do I disable dates AFTER the datepicker is added to the page. And second how do I disable a range between two dates, as it looks like the beforeShowDay method expects an array of dates rather than a range.
But how would I disable a range of dates? As I only have the start and
end dates.
One way could be to create an array of dates based on the start and end dates that you have. Use that array in beforeShowDay to disable the range.
Demo: http://jsfiddle.net/abhitalks/FAt66/1/
For example, Relevant portions of JS:
var startDate = "2014-06-15", // some start date
endDate = "2014-06-21", // some end date
dateRange = []; // array to hold the range
// populate the array
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
// use this array
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [dateRange.indexOf(dateString) == -1];
}
Now, you could set startDate and endDate whenever a date is selected. In the example fiddle I linked to above, the start and end dates are set whenever a date is selected in the two top inputs. The data array is populated when date is selected in the second input.
Note: The above example is additive, i.e. everytime you select a new range it gets added as disabled dates into the target. If you want to clear the existing disabled range before specifying a new range, then you could do a destroy and reattach the datepicker. (And also reset the dateRange array)
Demo 2: http://jsfiddle.net/abhitalks/FAt66/3/
Relevant portion of JS:
$("#dt").datepicker("destroy");
$("#dt").datepicker({
dateFormat : 'yy-mm-dd',
beforeShowDay: disableDates
});
var disableDates = function(dt) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', dt);
return [dateRange.indexOf(dateString) == -1];
}
Looking at your actual code, all you need is this:
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
addWeek($.datepicker.iso8601Week(new Date(dateText)), $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
for (var d = new Date(startDate);
d <= new Date(endDate);
d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('dd/mm/yyyy', d));
}
selectCurrentWeek();
},
beforeShowDay: disableDates,
...
This will keep adding the newly selected date ranges to the array and will additively keep on disabling. But, be cautioned that you will need an escape route when an already selected week is removed. In that case, you may work with multiple array which can be coalesced into one master array.
If there is a requirement to disable a list of dates or like if in any reservation kind of projects where we have to disable some dates throughout the process. So you can use following code,
$(function() {
//This array containes all the disabled array
datesToBeDisabled = ["2019-03-25", "2019-03-28"];
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
minDate : 0,
todayHighlight: 1,
beforeShowDay: function (date) {
var dateStr = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [datesToBeDisabled.indexOf(dateStr) == -1];
},
});
});
I used all the solutions but not worked but i made change in common jquery.datepick.js
Exisiting _isSelectable constructor function
_isSelectable: function(elem, date, onDate, minDate, maxDate) {
var dateInfo = (typeof onDate === 'boolean' ? {selectable: onDate} :
(!$.isFunction(onDate) ? {} : onDate.apply(elem, [date, true])));
//This function is modified by Savata to Block fridays on homepage
return (dateInfo.selectable !== false) &&
(!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime());
}
Changed to
_isSelectable: function(elem, date, onDate, minDate, maxDate) {
var dateInfo = (typeof onDate === 'boolean' ? {selectable: onDate} :
(!$.isFunction(onDate) ? {} : onDate.apply(elem, [date, true])));
return (dateInfo.selectable !== false) &&
(!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) && date.getDay() != 5;
/*Added last condition date.getDay() != 5 to block friday
In your case change accordingly
for sunday = 0 to saturday = 6
*/ }

Change the start week on Jquery datepicker ShowWeek

I'm working on a project utilizing the jQuery datepicker, and am trying to use the showWeek attribute to display the week number next to the calender.
My problem is that I don't want 'week 1' to start on the first of January, but instead on the first of August.
Is there any way I can Implement this?
Thanks
working with the next month not working for prev month so i have disabled prev month.
calender always open with August month if current month less than August than calender start from previous year August.
Working Demo http://jsfiddle.net/cse_tushar/dR429/4
$(document).ready(function () {
i = 0;
month_set = 8;
var d = new Date();
week = (Math.ceil(Math.round(((new Date(d.getFullYear() + 1, 1)) - (new Date(d.getFullYear(), 1))) / 86400000) / 7));
current_year = ((d.getMonth() + 1) >= month_set) ? d.getFullYear() : d.getFullYear() - 1;
function myWeekCalc() {
i++;
return i = (i > week) ? 0 : i;
}
$("#d1").datepicker({
showWeek: true,
defaultDate: new Date(current_year, month_set-1, 1),
calculateWeek: myWeekCalc,
onClose: function () {
i = 0;
},
onChangeMonthYear: function (year, month) {
var diff = month - month_set;
var d = new Date(month + ' 1' + ',' + year);
if (d.getDay() != '0') {
i--;
}
if (month == month_set) {
i = 0;
}
if (current_year != year && month == month_set) {
week = (Math.ceil(Math.round(((new Date(year + 1, 1)) - (new Date(year, 1))) / 86400000) / 7));
}
}
}).focus(function () {
$(".ui-datepicker-prev").remove();
});
});
Using jQuery Date Picker custom Week of Year calculation and Moment library to calculate the week of year based on your locale.
Please refer to this working example:
https://jsfiddle.net/amansour/sez8fLgt/
function myWeekCalc(dt) {
var dat = moment(dt).locale("en-US");
return dat.week();
// return dat.isoweek(); // you will have to use firstDay : 1
}
$(function(){
$("[type='date']").datepicker({
changeMonth: true,
changeYear: true,
showWeek: true,
firstDay: 0, // 1 being Monday, 0 being Sunday, 6 being Friday
calculateWeek: myWeekCalc,
dateFormat: "yy-mm-dd",
yearRange: "-12:+12"
});
});

Categories