jQuery UI Datepicker hiding previous months - javascript

I'm trying to create 12 months jquery UI Datepicker with date range selection.
I'm using
numberOfMonths: [12,1],
which is working fine
Problem is when i try to select two dates between two months (March,15,2016 to April,15,2016) calendar wills start from April i cant edit previous month dates, i want to keep 12 months in every condition in short i need 12 months jquery datepicker which can select two dates. my code is
<div id="jrange" class="dates">
<input type="text" id="startDate" size="10" placeholder="9 Mar" readonly>
<span id="spaceDash">–</span>
<input type="text" id="endDate" size="10" placeholder="10 Mar" readonly>
<div></div>
</div>
$(document).ready(function(){
$("#jrange div").datepicker({
minDate: 0,
numberOfMonths: [12,1],
dateFormat: "MM dd",
showMonthAfterYear: true,
beforeShowDay: function(date) {
var date1 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#startDate").val());
var date2 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#endDate").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#startDate").val());
var date2 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#endDate").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker("option", "minDate", dateText);
} else {
$("#input2").val(dateText);
$(this).datepicker("option", "minDate", null);
}
}
});

Related

Jquery ui datepicker preselect date that is not a sunday

I have modified the jquery ui datepicker to pre-select the day that is 2 days from now and I have also disabled Sundays in the datepicker. However, the input field is still being pre-filled with the Sunday if the Sunday is 2 days from now. How do I prevent this?
$(function() {
$("#delivery-date").datepicker({
minDate: +2,
maxDate: '+2M',
dateFormat: "DD, d MM yy",
showOn: "both",
buttonText: "Change",
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 0), ''];
}
}).datepicker("setDate", "0");
});
Assuming you would switch to the Next day, Monday, you can use conditional (ternary) operator.
Here is an example.
$(function() {
$("#delivery-date").datepicker({
minDate: new Date().getDay() + 2 == 7 ? 3 : 2,
maxDate: '+2M',
dateFormat: "DD, d MM yy",
showOn: "both",
buttonText: "Change",
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 0), ''];
}
}).datepicker("setDate", "0");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="delivery-date"></p>
If today is Friday (5), adding 2 days, would make it Sunday of the next week (7, or in JS: 0). So we can check for that.
Normally we might make a function:
function pickDay(n){
var d = new Date().getDay(); // Returns the day of the week: 5
if(d + n == 7){
return n + 1;
}
return n;
}
and then use it like so:
minDate: pickDay(2),
I tested this and it's not liked, there seems to be some timing issue.

Bootstrap datetimepicker showing two calendar months

Here it looks like:
I want it to just show one month with it ranging the dates from the minDate to maxDate. And this works good but it is showing two views for some reason..
Here is the JS:
var maxDate = new Date();
var minDate = $("#from").val();
var datePickerLimits= $("#from, #to").datetimepicker({
minDate: minDate,
maxDate: maxDate,
pickTime: false,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datetimepicker"),
date =
$.datetimepicker.parseDate(instance.settings.dateFormat ||
$.datetimepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datetimepicker("option", option, date);
}
});
Rails:
= text_field_tag :from_js, l((params[:from].to_datetime or
#item.date), format: :american_no_time), class: 'form-control
input-sm datetimepicker', id: 'from'
= text_field_tag :to_js, l((params[:to].to_datetime or
#item.date_end), format: :american_no_time), class: 'form-control
input-sm datetimepicker', id: 'to'
This is used with rails but it seems to be happening in the JS as the only thing that is being called is the class datetimepicker.
Add Startdate and EndDate in date picker
var today = new Date();
var lastDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
In your script add
var today = new Date(); //Get today's date
var lastDate = new Date(today.getFullYear(), today.getMonth() + 1, 0); //To get the last date of today's month
$("#datepicker").datepicker({
startDate: today,
endDate: lastDate
});
This fixed the problem.
var maxDate = new Date();
var minDate = $("#from").val();
$(function () {
$('#from').datetimepicker({
minDate: minDate,
maxDate: maxDate,
pickTime: false
});
$('#to').datetimepicker({
minDate: minDate,
maxDate: maxDate,
pickTime: false
});
});

jQuery .val not updating DOM on input date

So i seem to have found a problem im not sure if this is jQuery bug or it's just not possible but if any one has managed this could they tell me how.
I have a Date picker and i don't want to allow users to select dates in the past.
var d = new Date($(this).val());
var nowDate = new Date();
var nowDateParse = ""+
nowDate.getFullYear()+
(nowDate.getMonth()+1 < 10? "0"+(nowDate.getMonth()+1): (nowDate.getMonth()+1))+
(nowDate.getDate()+1 < 10? "0"+(nowDate.getDate()+1): (nowDate.getDate()+1));
var selDate = ""+
d.getFullYear()+
(d.getMonth()+1 < 10? "0"+(d.getMonth()+1): (d.getMonth()+1))+
(d.getDate()+1 < 10? "0"+(d.getDate()+1): (d.getDate()+1));
if(parseInt(nowDateParse) > parseInt(selDate)){
alert("You can only select dates in the future!");
$("#searchDate").attr("value", ""+
nowDate.getFullYear()+"-"
(nowDate.getMonth()+1 < 10? "0"+(nowDate.getMonth()+1): (nowDate.getMonth()+1))+"-"+
(nowDate.getDate()+1 < 10? "0"+(nowDate.getDate()+1): (nowDate.getDate()+1))
)
return false;
}
as you can see i have tired $("#searchDate").attr("value" as well as $("#searchDate").val( but both seem to cause the same problem.
So Date starts on the current date: 27/06/2016 (UK format for: 2016-06-27)
if the user selects a date before that E.G 26/06/2016 (UK format for: 2016-06-26)
it shows the alert but fails to change the date back to today's date.
I'm not against using Standard Javascript with out jQuery calls if thats what is needed.
NOTES:::
As a note this code looks quite complex due to the fact it's doing a date comparison and not a datetime comparison as Javascript's Date object is a datetime not just a date
Add this after the control of the date validity:
var dToday = new Date();
var day = ("0" + dToday.getDate()).slice(-2);
var month = ("0" + (dToday.getMonth()+1)).slice(-2);
today = dToday.getFullYear() + "-" + month + "-" + day;
$("#searchDate").val(today);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" id="searchDate">
You must create a new date object and set it as minDate when you initialize the datepickers
<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>
var dateToday = new Date();
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
minDate: dateToday,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
http://jsfiddle.net/dssoft32/qvmqawfd/

Want to Disable Sunday in date picker

Want to Disable Sunday,
<input id="datepicker"> var picker = new Pikaday({
disableDayFn: function(date)
{
// Disable Monday return date.getDay() === 1;
}, field: ...
$("#dp").datepicker({
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 0), ''];
}
});

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
*/ }

Categories