Graying out a specific date with jQuery UI doesn't work - javascript

With the code below, I'm trying to gray out 21/12/2020 because we don't ship until Tuesday(22/12/2020). I cannot find what is wrong in the code below. Please point out the error in the code that might be causing it not to work.
<script>
jQuery(document).ready( function() {
jQuery(function() {
jQuery("#ship_date").datepicker( {
var minDate;
// get current date
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var current_date = (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day + d.getFullYear() + '/';
if (current_date < new Date(11, 22, 2020) {
minDate = new Date( 11, 22, 2020 );
} else {
minDate = +1;
}
maxDate: '+2M',
beforeShowDay: jQuery.datepicker.noWeekends
} );
});
});
</script>

UPDATED the answer as per request from PKTG:
<script>
$( function() {
var cuttoffdate = new Date(2020,11, 22);
$( "#ship_date" ).datepicker(
{
maxDate: '+2M',
beforeShowDay: function (date) {
show = true;
if (date.getDay() === 0 || date.getDay() === 6) { show = false; }
if(date<cuttoffdate) { show=false;};
var display = [show, '', (show) ? '' : 'Not available'];
return display;
}
}
);
} );
</script>

Related

Javascript/Jquery-UI make reusable function that checks if dateTo is after dateFrom

I have 2 datepickers. #datepicker0 and #datepicker1 and the following code to check if the date_from is after date_to:
$('#datepicker0').datepicker({
dateFormat: 'yy-mm-dd'
});
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
if ($('#datepicker0').val() > $(this).val()) {
alert("Date problem");
$(this).val(null)
}
$(this).change();
}
}
$("#datepicker1").datepicker(valeDate).on("change", function() {
display("Change event");
I would like to remove the parameter #datepicker0 from the onSelect function in order to make the function reusable.
Could anyone show me how to make it?
function validateDate(datepicker, value) {
if (value > datepicker.val()) {
alert("Date problem")
datepicker.val(null)
}
datepicker.change()
}
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
validateDate($(this), $('#datepicker0').val())
}
}
Next time, please address questions like this (everything works but code require modifications) to code review (https://codereview.stackexchange.com/)
finally i used this code:
function datepickerValidator(startDate,endDate) {
var datepickerFrom = startDate;
var datepickerTo = endDate;
// returns the millisecond obtained from the string 'dd-mm-yy'
function getTimeMillis(dateString) {
var splittedFrom = dateString.split("-");
var day = splittedFrom[0];
var month = splittedFrom[1];
var year = splittedFrom[2];
var dateTmp = new Date(year + "-" + month + "-" + day);
var timeMillis = dateTmp.getTime();
return timeMillis;
}
var validateDatePickerOption = {dateFormat: 'dd-mm-yy',
onSelect: function() {
from = getTimeMillis(datepickerFrom.val());
to = getTimeMillis($(datepickerTo).val());
if ( from > to ) {
alert("Date problem: value 'To' must be after 'From'");
$(this).val(null)
}
}
}
return validateDatePickerOption;
}
and for each datepicker:
var from = $("#From");
var to = $("#To");
var datepickerOption = datepickerValidator(from,to);
from.datepicker(datepickerOption);
to.datepicker(datepickerOption);

Opening TO date, after selecting FROM date in datepicker range using each

I got a calendar range on a page, consisting of two inputs, #from-date and #to-date. If I select from date, I want the to date to be shown automatically.
HTML markup:
<div class="calendar-range">
<div class="filter-first date-from">
<input type="text" id="from-date" class="form-control form-control-main calendar-from datepicker">
<i class="fa fa-calendar"></i>
</div>
<div class="filter date-to">
<input type="text" id="to-date" class="form-control form-control-main calendar-to datepicker">
<i class="fa fa-calendar"></i>
</div>
</div>
This is the jQuery code:
body.find(".calendar-range").each(function (index, callback) {
var selectedToElement = $(this).find('.calendar-to');
var selectedToDay = selectedToElement.datepicker('getDate');
var selectedFromElement = $(this).find('.calendar-from');
var selectedFromDay = selectedFromElement.datepicker('getDate');
var numberOfMonths = 2;
if (body.width() < 768) {
numberOfMonths = 1;
}
var settings = {
changeMonth: false,
numberOfMonths: numberOfMonths,
dateFormat: dateFormat,
minDate: new Date(Date.now()),
maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
onSelect: function (dateText, object) {
selectedToDay = selectedToElement.datepicker('getDate');
selectedFromDay = selectedFromElement.datepicker('getDate');
selectedToElement.change();
selectedFromElement.change();
if ($(this).hasClass('calendar-from')) {
to.datepicker("option", "minDate", getDate(this.value));
} else if ($(this).hasClass('calendar-to')) {
from.datepicker("option", "maxDate", getDate(this.value));
}
},
beforeShow: function (input, inst) {
selectedToDay = selectedToElement.datepicker('getDate');
selectedFromDay = selectedFromElement.datepicker('getDate');
},
beforeShowDay: function (date) {
var d = date.getTime();
var cssClass = 'selected-date-range';
var defaultClass = '';
if (selectedToDay != null && d == selectedToDay.getTime()) {
cssClass = cssClass + ' selected-date-range-last';
defaultClass = defaultClass + ' selected-date-range-last';
} else if (selectedFromDay != null && d == selectedFromDay.getTime()) {
cssClass = cssClass + ' selected-date-range-first';
defaultClass = defaultClass + ' selected-date-range-first';
}
if (selectedFromDay != null && selectedToDay != null && d <= selectedToDay.getTime() && d >= selectedFromDay.getTime()) {
return [true, cssClass, ''];
}
return [true, defaultClass, ''];
},
onClose: function (input, object) {
if (object.id === "from-date") {
to.datepicker("show");
}
}
};
var from = selectedFromElement.datepicker(settings);
var to = selectedToElement.datepicker(settings);
});
I tried solving it with onClose, but this seems to iterate twice, and close the opened #to-date too. Is it possible to implement it without separating the two datepickers? (also something really weird happens with hiding/showing the datepickers)
Help appreciated, thx.
There are a number of improvements you can make. Here is a working example:
https://jsfiddle.net/Twisty/mcqra47o/
JavaScript
$(function() {
var body = $("body");
var dateFormat = "mm/dd/yy";
$(".calendar-range").each(function(index, callback) {
var selectedToElement = $(this).find('.calendar-to');
var selectedToDay = selectedToElement.val().length ? selectedToElement.datepicker('getDate') : new Date;
var selectedFromElement = $(this).find('.calendar-from');
var selectedFromDay = selectedFromElement.val().length ? selectedFromElement.datepicker('getDate') : new Date;
var numberOfMonths = 2;
if (body.width() < 768) {
numberOfMonths = 1;
}
var settings = {
changeMonth: false,
numberOfMonths: numberOfMonths,
dateFormat: dateFormat,
minDate: 0,
maxDate: "+1y",
onSelect: function(dateText, object) {
selectedToDay = selectedToElement.datepicker('getDate');
selectedFromDay = selectedFromElement.datepicker('getDate');
/*
selectedToElement.change();
selectedFromElement.change();
*/
if ($(this).hasClass('calendar-from')) {
selectedToElement.datepicker("option", "minDate", dateText);
} else if ($(this).hasClass('calendar-to')) {
selectedFromElement.datepicker("option", "maxDate", dateText);
}
},
beforeShow: function(input, inst) {
selectedToDay = selectedToElement.datepicker('getDate');
selectedFromDay = selectedFromElement.datepicker('getDate');
},
beforeShowDay: function(date) {
var d = date.getTime();
var cssClass = 'selected-date-range';
var defaultClass = '';
if (selectedToDay != null && d == selectedToDay.getTime()) {
cssClass = cssClass + ' selected-date-range-last';
defaultClass = defaultClass + ' selected-date-range-last';
} else if (selectedFromDay != null && d == selectedFromDay.getTime()) {
cssClass = cssClass + ' selected-date-range-first';
defaultClass = defaultClass + ' selected-date-range-first';
}
if (selectedFromDay != null && selectedToDay != null && d <= selectedToDay.getTime() && d >= selectedFromDay.getTime()) {
return [true, cssClass, ''];
}
return [true, defaultClass, ''];
},
/*
onClose: function(input, object) {
if (object.id === "from-date") {
to.datepicker("show");
}
}
*/
};
var from = selectedFromElement.datepicker(settings);
var to = selectedToElement.datepicker(settings);
});
});
First, we should not call .datepicker() to getDate before it's been initialized. So to set the following variables early, we can do this:
var selectedToDay = selectedToElement.val().length ? selectedToElement.datepicker('getDate') : new Date;
var selectedFromDay = selectedFromElement.val().length ? selectedFromElement.datepicker('getDate') : new Date;
For minDate and maxDate, we can check the API and see:
Multiple types supported:
Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.
I suggest using relative date formats if possible. For today, I used 0, and for 1 year, I used "+1y".
When a selection is made change is fired anyway, so I commented this out. If it is needed for something else, I would suggest looking at .tragger("change").
The onSelect option passes dateText in, so we can use that to set the new minDate and maxDate as needed.
Hopefully that addresses everything and works as you'd desired.

Changing default display date to todays date in Datepicker

the date is defaulting to tomorrow's date instead of todays date.
the website is www.estesparkcabins.com/stiva/book.html
I think i narrowed down where the code needs to be changed. Let me know what you think. Thank you so much.
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
It also has other js files like this:
}).on("focusin.hb", ".hbSelectorDatepick", function (e) {
if (datepicker) {
var $this = pjQ.$(this),
dOpts = {
dateFormat: $this.data("dformat"),
firstDay: $this.data("fday"),
monthNamesShort: self.opts.month_names,
dayNamesMin: self.opts.day_names,
minDate: 1,
changeMonth: true
};
$this.datepicker(pjQ.$.extend(dOpts, {
beforeShow: function (input, ui) {
var dt_from, $chain,
name = ui.input.attr("name");
if
(name == "date_from") {
ui.input.datepicker("option", "minDate", 0);
} else if (name == "date_to") {
$chain = ui.input.closest("form").find("input[name='date_from']");
dt_from = $chain.datepicker(dOpts).datepicker("getDate");
if (dt_from != null) {
ui.input.datepicker("option", "minDate", new Date(dt_from.getTime() + 86400*1000));
}
}
ui.dpDiv.addClass('stivaDatepicker');
},
onSelect: function (dateText, ui) {
var dt_from, dt_to, $dt_to;
if (ui.input.attr("name") == "date_from") {
$dt_to = ui.input.closest("form").find("input[name='date_to']");
dt_from = ui.input.datepicker(dOpts).datepicker("getDate");
dt_to = $dt_to.datepicker(dOpts).datepicker("getDate");
if (dt_from != null && dt_to != null && dt_from.getTime() > dt_to.getTime()) {
$dt_to.datepicker("option", "minDate", new Date(dt_from.getTime() + 86400*1000));
}
}
}
}));
}
This is quite simple you do not need to change anything. Just change the initialization code for date-picker.
$(".your_element").datepicker('setDate', new Date());

jquery datePicker beforeShowDay not working for 2014

Hi i am trying to get jquery datePicker to get working for 2014 Year dates. it works Perfect with 2013 dates but not for 2014 date
here is my code
<script>
$(document).ready(function () {
var enabledDays = ['11-30-2013', '12-14-2013', '12-21-2013', '01-11-2014', '01-11-2014', '01-25-2014', '02-08-2014', '02-22-2014'];
function enableAllTheseDays(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) {
return [true];
}
}
return [false];
}
$('#datepicker').datepicker({
dateFormat: 'mm-dd-yyyy',
beforeShowDay: enableAllTheseDays,
onSelect: showDate
});
});
</script>
<script>
function showDate(date) {
alert("Event is on " + date);
}
</script>
any solution to get this working for 2014 dates aswell..? Thanks
demo
Try this code the problem is leading zero's in the date and month for 2014.
<script>
$(document).ready(function () {
var enabledDays = ['11-30-2013', '12-14-2013', '12-21-2013', '01-11-2014', '01-11-2014', '01-25-2014', '02-08-2014', '02-22-2014'];
function enableAllTheseDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear(),mon="",day="";
for (i = 0; i < enabledDays.length; i++) {
m=m+1;
mon=m.toString();
if(mon.length <2){
m="0"+m;
}
day=d.toString();
if(day.length <2){
d="0"+d;
}
if ($.inArray( m + '-' + d + '-' + y, enabledDays) != -1) {
return [true];
}
}
return [false];
}
$('#datepicker').datepicker({
dateFormat: 'mm-dd-yyyy',
beforeShowDay: enableAllTheseDays,
onSelect: showDate
});
});
</script>
<script>
function showDate(date) {
alert("Event is on " + date);
}
</script>

How to Add a day on jquery calendar

I am using this code to create a jquery calendar on my page
$(function(){
//set the datepicker
var dateToday = new Date();
$('#pikdate').datetimepicker({
minDate: dateToday,
dateFormat: 'dd/mm/yy',
defaultDate: '+1w'
});
});
how to add a day in this calendar that calendar should be start from after 24 hour.
You can do like this.
$('#pikdate').datepicker({
minDate: dateToday,
dateFormat: 'dd/mm/yy',
defaultDate: '+1w'
});
You could add a day in the date you are setting as "minDate".
See the example here (I changed your code):
$(function(){
//set the datepicker
var dateToday = new Date();
dateToday.addDays(1); // it will add one day to the current date (ps: add the following functions)
$('#pikdate').datetimepicker({
minDate: dateToday,
dateFormat: 'dd/mm/yy',
defaultDate: '+1w'
});
});
But to make the "addDays" function work you must create the function as you can see down.
I always create 7 functions, to work with date in JS: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.
You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/
This are the functions:
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
return this;
};
Date.prototype.addMinutes = function(minutes) {
this.setMinutes(this.getMinutes() + minutes);
return this;
};
Date.prototype.addHours = function(hours) {
this.setHours(this.getHours() + hours);
return this;
};
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addWeeks = function(weeks) {
this.addDays(weeks*7);
return this;
};
Date.prototype.addMonths = function (months) {
var dt = this.getDate();
this.setMonth(this.getMonth() + months);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Date.prototype.addYears = function(years) {
var dt = this.getDate();
this.setFullYear(this.getFullYear() + years);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
They are propotype functions it means that every variable from the type "Date" will have this functions.

Categories