Block weekends with jQuery Datepicker inside function? - javascript

I have the following code that blocks any date after 10am, I also need it to block weekends. How do I do this within my current function? I've tried a number of different solutions and had no luck.
var d = new Date();
var $checkTime = d.getHours();
jQuery(function() {
if ($checkTime >= 10) {
jQuery("#date").datepicker( {
minDate: +2,
maxDate: '+6M',
dateFormat: 'dd MM yy',
beforeShowDay: checkBadDates
});
} else {
jQuery("#date").datepicker( {
minDate: +1,
maxDate: '+6M',
dateFormat: 'dd MM yy',
beforeShowDay: checkBadDates
});
}
});
var $myBadDates = new Array({{ settings.bad_delivery_date }});
function checkBadDates(mydate){
var $return=true;
var $returnclass ="available";
var $checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}

One built in function exists, called noWeekends, that prevents the selection of weekend days.
$(".selector").datepicker({ beforeShowDay: $.datepicker.noWeekends })
To combine the two, you could do something like (assuming the bad date function from above):
$(".selector").datepicker({ beforeShowDay: noWeekendsOrBadDates})
function noWeekendsOrBadDates(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return checkBadDates(date);
} else {
return noWeekend;
}
}
function checkBadDates(mydate){
var $return=true;
var $returnclass ="available";
var $checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}

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);

Jquery Datepicker Limited to the month and year of another datepicker

I have an issue. I need a datepicker which will limit the user to choose the date.
So it goes like this:
1) First input, I should be able to pick whatever day, month, and year I want.
2) Second input, I should be able to pick a day if it is greater than First Input's day, from the same month/year of the First Input. Else alert an error.
EDIT - code:
http://jsfiddle.net/wc6jcpka/
var dates = $("input[id$='startDate'], input[id$='endDate']").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
onSelect: function (selectedDate) {
var option = this.id == $("input[id$='startDate']")[0].id ? "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);
}
});
Below will work as per your requirement:
var txtTranDate = $("#startDate");
var txtTranDateTo = $("#endDate");
txtTranDate.datepicker({
defaultDate: 0,
changeMonth: true,
changeYear: true,
dateFormat: dateFormat,
maxDate: 0,
numberOfMonths: 1
}).on("change", function () {
var dcal = getDate(this);
if (txtTranDate.val() !== '' && dcal === null) {
txtTranDate.prop("value", "");
txtTranDateTo.prop("value", "");
} else {
txtTranDateTo.datepicker("option", "minDate", getDate(this));
}
});
txtTranDateTo.datepicker({
defaultDate: 0,
changeMonth: true,
changeYear: true,
maxDate: 0,
dateFormat: dateFormat,
numberOfMonths: 1
}).on("change", function () {
var dcal = getDate(this);
if (txtTranDateTo.val() !== '' && dcal === null) {
txtTranDate.prop("value", "");
txtTranDateTo.prop("value", "");
} else {
txtTranDate.datepicker("option", "maxDate", getDate(this));
}
});
UPDATE Method to check if valid date is entered
function getDate(element) {
var date;
try {
date = $.datepicker.parseDate(dateFormat, element.value);
} catch (error) {
date = null;
}
return date;
}
#Gaurav P gave me a hint, but I had to do some modifications so that the code works.
Here is the code:
var txtTranDate = $("input[id$='startDate']");
var txtTranDateTo = $("input[id$='endDate']");
txtTranDate.datepicker({
defaultDate: 0,
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
}).on("change", function () {
var date = this.value;
var values = date.split("/");
var lastDate = new Date(values[2], values[1] - 1, daysInMonth(values[1], values[2]));
var formatted = $.datepicker.formatDate("dd/mm/yy", lastDate);
txtTranDateTo.datepicker("option", "minDate", getDate(this));
txtTranDateTo.datepicker("option", "maxDate", formatted);
});
txtTranDateTo.datepicker({
defaultDate: 0,
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy',
numberOfMonths: 1
}).on("change", function() {
});
function getDate(element) {
var date;
try {
date = $.datepicker.parseDate('dd/mm/yy', element.value);
} catch (error) {
date = null;
}
return date;
}
This will also work, just edited some of your code.
http://jsfiddle.net/wc6jcpka/2/
$(function(){
var dates = $("input[id$='startDate'], input[id$='endDate']").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
onSelect: function (selectedDate) {
var endDateInput = $("#endDate").val();
var startDateInput = $("#startDate").val();
if(endDateInput != '' && startDateInput != ''){
var endDate = new Date();
endDate.setMonth (parseInt(endDateInput.substr(3, 6), 10) - 1);
endDate.setDate (parseInt(endDateInput.substr(0, 3), 10));
endDate.setYear (parseInt(endDateInput.substr(6, 10), 10));
var startDate = new Date();
startDate.setMonth (parseInt(startDateInput.substr(3, 6), 10) - 1);
startDate.setDate (parseInt(startDateInput.substr(0, 3), 10));
startDate.setYear (parseInt(startDateInput.substr(6, 10), 10));
if(startDate.getDate() >= endDate.getDate() || startDate.getMonth() != endDate.getMonth() || startDate.getYear() != endDate.getYear()){
alert("Error");
}
}
}
});
});

Highlight daterange in jQuery UI datepicker on hover

I'm having some trouble with my jQuery UI Datepicker.
I've managed to make it highlight my daterange when I select a start and end date (e.g. 2015/12/02 - 2015/12/08) - then the dates between is highlighted in a green color.
My question is now - can I highligt a daterange BEFORE I select an end date?
Here's an example:
http://stephencelis.github.io/timeframe/#example_information
When I select a startdate, it highlights the daterange until I select my desired end-date. I'm not sure if it's something that can be done in jQuery UI Datepicker - and if not, then I have to find something else - but it's worth a try asking in here :)
Here is my code so far:
$(function() {
var disabledDate = ["13-12-2015", "14-12-2015", "15-12-2015"];
$.datepicker.setDefaults($.datepicker.regional["da"]);
$("#datepicker").datepicker({
minDate: 0,
/* numberOfMonths: [4,2], */
numberOfMonths: 2,
firstDay: 1,
inline: true,
beforeShowDay: function(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
if(disabledDate.indexOf(string) == -1) {
} else {
return[false, 'disabled-dates'];
};
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateFrom").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateTo").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "selected-dates" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateFrom").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateTo").val());
var selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
if (!date1 || date2) {
$("#chooseDateFrom").val(dateText);
$("#chooseDateTo").val("");
$(this).datepicker("option", "minDate", dateText);
} else if( selectedDate < date1 ) {
$("#chooseDateTo").val( $("#chooseDateFrom").val() );
$("#chooseDateFrom").val( dateText );
$(this).datepicker("option", "minDate", dateText);
} else {
$("#chooseDateTo").val(dateText);
$(this).datepicker("option", "minDate", null);
}
}
});
});
I hope someone can help me a bit :) I'm kinda stuck here :/
This would help you....
$(document).ready(function(){
var disabledDate = ["13-12-2015", "14-12-2015", "15-12-2015"];
$("#datepicker").datepicker({
minDate: 0,
/* numberOfMonths: [4,2], */
numberOfMonths: 2,
firstDay: 1,
inline: true,
beforeShowDay: function(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
if(disabledDate.indexOf(string) == -1) {
} else {
return[false, 'disabled-dates'];
};
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateFrom").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateTo").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "selected-dates" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateFrom").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#chooseDateTo").val());
var selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
if (!date1 || date2) {
$("#chooseDateFrom").val(dateText);
$("#chooseDateTo").val("");
$(this).datepicker("option", "minDate", dateText);
} else if( selectedDate < date1 ) {
$("#chooseDateTo").val( $("#chooseDateFrom").val() );
$("#chooseDateFrom").val( dateText );
$(this).datepicker("option", "minDate", dateText);
} else {
$("#chooseDateTo").val(dateText);
$(this).datepicker("option", "minDate", null);
}
setTimeout("$('a.ui-state-default').attr('onmouseover','setBackColor(this)');",1000);
}
});
$('a.ui-state-default').attr('onmouseover','setBackColor(this)');
});
function setBackColor(object){
var day1=parseInt($(object).html());
var month1=parseInt($(object).parents("td").attr("data-month"));
var year1=parseInt($(object).parents("td").attr("data-year"));
var date1=new Date(year1,month1, day1);
//$("#chooseDateFrom").val(date1);
if(Date.parse(document.getElementById('chooseDateFrom').value)){
$("a.ui-state-default").each(function(){
var obj = this;
var day=parseInt($(obj).html());
var month=parseInt($(obj).parents("td").attr("data-month"));
var year=parseInt($(obj).parents("td").attr("data-year"));
var date=new Date(year,month, day);
if(new Date($("#chooseDateFrom").val())<=date && date<=date1){
$(obj).css("background-color","#78F764");
}else{
$(obj).css("background-color",'#e6e6e6');
}
});
}
}

Change range datepicker (jquery)

I have a question regarding jquery.ui datepicker.
I have a project where the week starts on Friday.
That I have no problem with that.
The thing is datepicker not find the way to make the select that I have for weeks, beginning with Friday and also select default Thursday click anywhere for that week.
In summary:
Week Starts Thursday.
The Selection of the week begins Thursday (range)
OnSelect Automatically switches to the selected week Thursday.
Can you help?
My 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( {
showOtherMonths: true,
selectOtherMonths: true,
firstDay: 5,
dateFormat: "dd/mm/yy",
maxDate : "+0",
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;
$('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
//window.location = '<?php echo HTTP_URI; ?>ranking/week?day=' + dateText + '';
},
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'); });
});
Yeep! I find my own solution.
My code
$(function() {
var selectCurrentWeek = function(callback) {
window.setTimeout(function () {
$(".week-picker").find("a.ui-state-active").parents("tr").find("a.ui-state-default").each(function(key, node) {
$(this).addClass("ui-state-active");
});
callback();
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
firstDay: 5,
dateFormat: "dd/mm/yy",
maxDate : "+0",
onSelect: function(dateText, inst) {
selectCurrentWeek(function() {
var startDayy = $(".week-picker").find("a.ui-state-active").eq(0);
var EndDayy = $(".week-picker").find("a.ui-state-active").eq(6);
var startDay = startDayy.text();
var EndDay= EndDayy.text();
var monthStart = startDayy.parent().attr('data-month');
var monthEnd= EndDayy.parent().attr('data-month');
var yearStart = startDayy.parent().attr('data-year');
var yearEnd = EndDayy.parent().attr('data-year');
if(monthStart < 10){ monthStart = '0'+monthStart; }
if(monthEnd < 10){ monthEnd = '0'+monthEnd; }
var CompleteStartDay = startDay +'/'+ monthStart +'/'+yearStart;
var CompleteEndDay = EndDay +'/'+ monthEnd +'/'+yearEnd;
$('#startDate').text(CompleteStartDay);
$('#endDate').text(CompleteEndDay);
//window.location = '<?php echo HTTP_URI; ?>ranking/week?day=' + CompleteStartDay + '';
});
}
});
});

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