Related
I have three <input> elements in my form.
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">
out of which first and second accepts a date chosen from Bootstrap Datepicker and the last one displays total number of days.
The total number of days is calculated excluding weekends( Saturdays and Sundays). I now want to achieve a functionality as in, when I disable a set of dates using datesDisabled option, those disabled dates should not be counted to form total no. of days. How to check whether a date is disabled in Bootstrap Datepicker ?
Here is a quick JS Fiddle to my code.
Below is my JS.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1;//adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
});
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if ( !((dayOfWeek == 6) || (dayOfWeek == 0)) )
count++;
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
If anyone could help me with this, it'll be of great help.
Working example: https://jsfiddle.net/cCrul/qLt6k0yv/
I just declared datesDisables as a variable:
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
and I use it to check if curDate is in that array before executing count++:
if (
!((dayOfWeek == 6) || (dayOfWeek == 0)) &&
(datesDisabled.indexOf(formatDate(curDate)) == -1)
) {
count++;
}
formatDate() function defined in the jsfiddle code.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1; //adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if (!((dayOfWeek == 6) || (dayOfWeek == 0)) && (datesDisabled.indexOf(formatDate(curDate)) == -1)) {
console.log(formatDate(curDate));
count++;
}
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day, month, year].join('-');
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">
I want to disable all the Sunday,Monday and Wednesday from my jquery date-picker. I am trying to do this using the following code sample -
jQuery(document).ready(function($) {
$(".datepicker").datepicker({
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 1), ''];
}
})
});
This code disable all Mondays from the calender. How can i disable all Sunday and Wednesdays too?
try this code
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 0), ''];
}
});
$(".datepicker").datepicker({
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 1 && day != 3 && day != 0), ''];
}
});
The days of week go as 0 - Sunday, 1 - Monday and so on.
So day != DayNumber will solve it for you.
Fiddle
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
*/ }
I have the following JavaScript code that uses of a StartDate & EndDate field.
What this code does is to restrict the dates on the EndDate field to the day you have chosen in the StartDate field.
What I am trying to do is to restrict time as well, for example the "datetimepicker" consists of a drop-down with Hours.
How do I restrict the EndDate field to one hour(according to the hour I have chosen from the StartDate field plus one) and maybe disable the rest of available hours?
$(document).ready(function () {
var dates = $('#StartDate, #EndDate').datetimepicker({
dateFormat: 'dd/mm/yy',
hourMin: 9,
hourMax: 17,
minDate: '1',
maxDate: null,
controlType: 'select',
timeFormat: 'hh:mm tt',
beforeShowDay: $.datepicker.noWeekends,
firstDay: 1,
changeFirstDay: false,
onSelect: function (selectedDate) {
var option = this.id == "StartDate" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datetimepicker._defaults.dateFormat,
selectedDate, instance.settings);
var edate;
var otherOption;
var d;
if (option == "minDate") {
otherOption = "maxDate";
d = date.getDate() + 0;
}
else if (option == "maxDate") {
otherOption = "minDate";
d = date.getDate() - 0;
}
var m = date.getMonth();
var y = date.getFullYear();
edate = new Date(y, m, d);
dates.not(this).datetimepicker("option", option, date);
dates.not(this).datetimepicker("option", otherOption, edate);
}
});
});
If you are using this plugin:
DateTimePicker
, then you can:
$('#rest_example_3').datetimepicker({
minDate: new Date(2010, 11, 20, 8, 30),
maxDate: new Date(2010, 11, 31, 17, 30)
});
Basically you need pass min date and end date with hours
Using this code i can enable only sundays. but how to disable sundays, if it is even week of the year.
function settings(date) {
if (date.getDay() == 0) {
return [true, "", "Works"];
} else {
return [false, "", ""];
}
}
$i("#searchsectionbarids").datepicker({
altField: "#alternate",
altFormat: "DD",
dateFormat: 'dd/mm/yy',
beforeShowDay: settings
});
use this to get the week number of the year:
Date.prototype.getWeek = function () {
var firstDay = new Date(this.getFullYear(), 0, 1);
var today = new Date(this.getFullYear(), this.getMonth(), this.getDate());
var dayOfYear = ((today - firstDay + 1) / 86400000);
return Math.ceil(dayOfYear / 7)
};
and then
function settings(date) {
if (date.getDay() == 0 && date.getWeek() % 2 == 1) {
return [true, "", "Works"];
} else {
return [false, "", ""];
}
}
Firstly, you must check the week is even or not
You can reference at
Get week of year in JavaScript like in PHP
Then you use your logic to setting your calendar
Good luck