Drupal 6 datepicker, blocking out weekends and certain holidays - javascript

A friend of mine has a Drupal 6 site where users are able to select a future date for a delivery. Recently, several customers have been selecting weekends and holidays for delivery dates, and my friend would like to prevent them from doing so.
This is the code we're currently using to block out weekends. Can someone help modify it to also block out Christmas and New Years Eve?
Thanks very much!
drupal_add_js("
Drupal.behaviors.date_popup = function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], function(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// CUSTOM
datePopup.settings.beforeShowDay = function(date) {
var day = date.getDay();
return [(day != 0 && day != 6), ''];
}
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
}
}
});
}
};
",'inline');
UPDATE:
I ended up doing the following, which works for our needs:
drupal_add_js("
Drupal.behaviors.date_popup = function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], function(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// CUSTOM
datePopup.settings.beforeShowDay = function(date) {
var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
var closedDates = [[12, 31, 2015], [12, 25, 2015]];
var closedDays = [[Saturday], [Sunday]];
for (var i = 0; i < closedDays.length; i++) {
if (day == closedDays[i][0]) {
return [false];
}
}
for (i = 0; i < closedDates.length; i++) {
if (date.getMonth() == closedDates[i][0] - 1 &&
date.getDate() == closedDates[i][1] &&
date.getFullYear() == closedDates[i][2]) {
return [false];
}
}
return [true];
}
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
}
}
});
}
};
",'inline');

Related

Disable specific dates and enable specific days of the week in jQuery datepicker

I'm trying to disable specific dates and enable only specific days of the week on a jQuery UI datepicker.
This is inside a Wordpress/Woocommerce theme and I'm trying to solve some bugs but I'm here for hours trying to figure out for a solution and even tried every solution I found on StackOverflow and other websites, but nothing seems to work.
My objective is to enable only chosen days of the week to be available, but when a date is chosen and bought, I need to disable it too. I successfully disabled the days of the week that I need to be disabled, but I can't do even a hardcoded prototype about the bought dates that should be disabled.
The code (with some hardcoded sample):
$(document).ready(function(){
var available_days = ["3"]; //it comes from the database
var today = new Date();
var tour_start_date = new Date( 1525132800000 ); //it comes from the database
var tour_end_date = new Date( 1546214400000 ); //it comes from the database
var available_first_date = tour_end_date;
var lang = 'en_UK';
lang = lang.replace( '_', '-' );
today.setHours(0, 0, 0, 0);
tour_start_date.setHours(0, 0, 0, 0);
tour_end_date.setHours(0, 0, 0, 0);
if ( today > tour_start_date ) {
tour_start_date = today;
}
function DisableDays(date) {
var day = date.getDay();
if ( available_days.length == 0 ) {
if ( available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
return true;
}
if ( $.inArray( day.toString(), available_days ) >= 0 ) {
if ( available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
return true;
} else {
return false;
}
}
if ( $('input.date-pick').length ) {
if ( lang.substring( 0, 2 ) != 'fa' ) {
$('input.date-pick').datepicker({
startDate: tour_start_date,
endDate: tour_end_date,
beforeShowDay: DisableDays,
language: lang
});
$('input[name="date"]').datepicker( 'setDate', available_first_date );
} else {
var date_format = $('input.date-pick').data('date-format');
$('input.date-pick').persianDatepicker({
observer: true,
format: date_format.toUpperCase(),
});
}
}
});
Please review: http://api.jqueryui.com/datepicker/#option-beforeShowDay
A function that takes a date as a parameter and must return an array with:
[0]: true/false indicating whether or not this date is selectable
[1]: a CSS class name to add to the date's cell or "" for the default presentation
[2]: an optional popup tooltip for this date
The issue in your code was that you were only returning true or false when an Array was needed. For example:
$(function() {
var available_days = ["3", "5"]; //it comes from the database
var today = new Date();
var tour_start_date = new Date(1525132800000); //it comes from the database
var tour_end_date = new Date(1546214400000); //it comes from the database
var available_first_date = tour_end_date;
var lang = 'en_UK';
lang = lang.replace('_', '-');
today.setHours(0, 0, 0, 0);
tour_start_date.setHours(0, 0, 0, 0);
tour_end_date.setHours(0, 0, 0, 0);
if (today > tour_start_date) {
tour_start_date = today;
}
function DisableDays(date) {
var day = date.getDay();
var found = false;
if (available_days.length == 0) {
if (available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
found = true;
}
if ($.inArray(day.toString(), available_days) >= 0) {
console.log(day + " in Array");
if (available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
found = true;
}
console.log(day, found);
return [found, "tour-date", "Tour Date"];
}
if ($('input.date-pick').length) {
if (lang.substring(0, 2) != 'fa') {
$('input.date-pick').datepicker({
startDate: tour_start_date,
endDate: tour_end_date,
beforeShowDay: DisableDays,
language: lang
});
$('input[name="date"]').datepicker('setDate', available_first_date);
} else {
var date_format = $('input.date-pick').data('date-format');
$('input.date-pick').persianDatepicker({
observer: true,
format: date_format.toUpperCase(),
});
}
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Date: <input type="text" class="date-pick" name="date" />

How to override event.stopPropagation(),preventDefault().stopImmediatePropagation()

I am trying to modify Jira Tempo plugin's plan work form. So in the tempo time sheet page
I have a button who has 2 actions bind-ed, one is a click action and one is a focus out.
the click action opens a popup. and the focus out verifies the form in the popup. I need the clik action to be executed first and then the focus out.
The problem is when the popup opens there is a call to all of the three functions.
event.stopPropagation().preventDefault().stopImmediatePropagation(); so the focus out does not fire in chrome.
In IE10 and Firefox works great.
Can i override jQuery basic function ofevent.stopPropagation().preventDefault().stopImmediatePropagation() to do not apply for that button?
all three, maybe?
I tried this:
(function () {
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
stopPropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (e && e.stopPropagation) {
e.stopPropagation();
}
}
},
preventDefault: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (e && e.preventDefault) {
e.preventDefault();
}
}
},
stopImmediatePropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if (e && e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
}
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
})();
UPDATE:
I don't have control on what the click function does, but i have control on the focus out, I have made some test and i looks like Chrome does not see the focus out event, because the element is hidden before the focus out occurs ( it is a popup button).
I managed to call my functions with mouse out event but this does not work on IE so I have to bind separate event listener for IE and Chrome,Firefox,Safari.
Can you help with some browser detection examples.
UPDATE 2:
My problem solved with a different listener to the popup element. ex:
jQuery(document).ready(function ($) {
var currentUser = null;
var selected = null;
var opened = null;
var formOpened = null;
var activityField = null;
var activitySelected = null;
var popupBody = null;
var formOpened = null;
var periodCheckbox = null;
var dateField = null;
var endDateField = null;
var plannedHours = null;
var periodselected = null;
var days = 1;
var startdate = 0;
var enddate = 0;
var planButton = $('#tempo-plan-button');
//this is the default LM-Holiday activity ID set this
value to corespond with the value on jira tempo form.
var holidayid = "10100";
var holidaysLeft = 21; /*
$('#tempo-plan-button').click(function () {
alert("click event");
});
$('#tempo-plan-button').focusin(function () {
alert("focus event");
});
$('#tempo-plan-button').hover(function () {
alert("hover event");
});
$('#tempo-plan-button').mouseleave(function () {
alert("mouse leave event");
});
$('#tempo-plan-button').mouseout(function () {
alert("mouse out event");
}); */
$('body').one('focus', 'div[class="aui-popup aui-dialog"]', function (event) {
$('div[class="aui-popup aui-dialog"]').each(function () {
popupBody = $(this).find(".dialog-components");
if ($(this).find(".dialog-title").hasClass("tempo-add-button") === false) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === null) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").click(function () {
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
});
} else {
j = 0;
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
}
;
}
;
return false;
});
$.ajax({
type: "GET",
url: location.protocol + '//' + location.host + "/rest/api/2/myself",
success: function (response) {
currentUser = $.parseJSON(response);
},
error: function (response) {
alert("Eroare" + response.result);
}
});
return false;
});
});
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1)
return -1; // error code if dates transposed
var iWeekday1 = dDate1.getDay(); // day of week
var iWeekday2 = dDate2.getDay();
iWeekday1 = (iWeekday1 === 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
iWeekday2 = (iWeekday2 === 0) ? 7 : iWeekday2;
if ((iWeekday1 > 5) && (iWeekday2 > 5))
iAdjust = 1; // adjustment if both days on weekend
iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000);
if (iWeekday1 <= iWeekday2) {
iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1);
} else {
iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2);
}
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive
}
function parseDate(s) {
var lastSlash = s.lastIndexOf("/");
var years = s.substring(lastSlash + 1);
years = "20" + years;
s = s.replaceAt(lastSlash + 1, years);
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = s.replace(pattern, function (match, p1, p2, p3) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return (months.indexOf(p2) + 1) + "/" + (p1) + "/" + p3;
});
return new Date(result);
}
String.prototype.replaceAt = function (index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
};
function propStopped(event) {
var msg = "";
if (event.isPropagationStopped()) {
msg = "called";
} else {
msg = "not called";
}
alert(msg);
}
Thanks.
Did you mean this?
Event.prototype.stopPropagation = function(){ alert('123') }
$('input').on('click',function(e){
e.stopPropagation();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='click' />
From the question, it is unclear as to which code you control. I am reading between the lines that perhaps you control the function bound to the click event for the button, but you do not control the function bound to the focusout event, which is why you need to work around those calls.
If you want to control of execution of the events and make sure that yours happen first, it's possible to do this with something like jQuery.bindUp, just so long as the events are of the same type. In that way, you don't care if the other handler tries to call stopPropagation etc. because your handler will get to execute first anyway.
Given that, is it possible to restructure your code so that the logic you control (the part which needs to happen first!) is of the same event type as the existing event handler, and then use jQuery.bindUp to ensure that it gets executed before the event handler that you do not control? You can still bind to the click event if you need it, just so long as the dependent business logic is moved to the focusout event.
(If my assumptions are not correct, it would be helpful if you could update the question to describe the problem constraints in more detail.)

jQuery Datepicker close datepicker after selected date

HTML:
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="example1">
</div>
</div>
jQuery:
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
I use bootstrap datepicker.
When I click to datepicker it opens and I select any date.
My question:
If I choose date from datepicker, I want to close datepicker popup.
Which event do i need to use in order to close datepicker on select date?
Edited:
I have found a solution
This works
$(document).mouseup(function (e) {
$('#example1').Close();
});
But this below does not work why ?
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Actually you don't need to replace this all (#Ben Rhouma Zied answere)....
There are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.
HTML
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
jQuery
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
this is all you have to do :)
HERE IS A FIDDLE to see whats happening.
Fiddleupdate on 13 of July 2016: CDN wasnt present anymore
According to your EDIT:
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).
Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!
Thats it :)
EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
.hero-unit{
float: left;
width: 210px;
margin-right: 25px;
}
.hero-unit input{
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
There is another code that's works for me (jQuery).
$(".datepicker").datepicker({
format: "dd/mm/yyyy",
autoHide: true
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />
Date: <input type="text" readonly="true" class="datepicker">
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
Just add this option to Datepicker component:
forceParse: false
Example:
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
defaultDate: 'now',
forceParse: false,
endDate: "today"
});

Datepicker automatically hide on month or year select

I can go back from date to year in datepicker. But when I try to come back to date, when i clicked on year, datepicker automatically hide.
var datePickerOptions = this.data || {};
datePickerOptions.format = datePickerOptions.format || "mm-dd-yyyy";
datePickerOptions.language = datePickerOptions.language || this.lang.code;
var $context = this;
var dateContainer = this.container.find(".datepicker");
dateContainer.datepicker(datePickerOptions).on('changeDate', function (ev) {
// here i'm getting the value
});
This because of bootstrap-datepicker.js .
on click event you can find like following.
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1);
this.fill();
}
instead of this.fill(), if you use like following code, this will work as you expected.
if (target.is('.month')) {
if (!this._o.changeMonth) {
this.fill();
}
}
else {
if (!this._o.changeYear) {
this.fill();
}
}
I hope, this will help you. :-)

Calling a function on Christmas day

I'm having a little bit of trouble trying to make it 'snow' only on Christmas day. I figured out how to grab the day but I'm not sure how make it call SnowStorm() correctly.
var christmas = {
month: 11,
date: 25
}
function isItChristmas() {
var now = new Date();
var isChristmas = (now.getMonth() == christmas.month && now.getDate() == christmas.date);
if (isChristmas)
return ;
else
return ;
}
var snowStorm = null;
function SnowStorm() {
(snowstorm code)
}
snowStorm = new SnowStorm();
Here's the version if you are planning to make a function (not a class):
var christmas = {
month: 12,
date: 25
}
function isItChristmas() {
var now = new Date();
return (now.getMonth() == christmas.month && now.getDate() == christmas.date);
}
if (isItChristmas()){
SnowStorm();
}else{
//not a christmas
}
function SnowStorm() {
(snowstorm code)
}
Here's the one if you are planning to make a class:
var christmas = {
month: 12,
date: 25
}
function isItChristmas() {
var now = new Date();
return (now.getMonth() == christmas.month && now.getDate() == christmas.date);
}
var storm = new SnowStorm();
if (isItChristmas()){
storm.Snow();
}else{
//not a christmas
}
function SnowStorm() {
this.Snow = function(){
(snowstorm code)
}
}
First, you are not returning anything on the isItChristmas function.
Second, in the SnowStorm function just add
if (isItChristmas) {
(your code here)
}
You need to return a boolean value from the isItChristmas function:
function isItChristmas() {
var now = new Date();
return (now.getMonth() + 1 == christmas.month &&
now.getDate() == christmas.date);
}
and then call it:
function SnowStorm() {
if (isItChristmas()) {
// your snowstorm code here
// that will execute only on Christmas
}
}
By the way you will notice that the .getMonth() method returns the month from 0 to 11, so you need to add 1 as shown in my example, otherwise your code will run on 25th of November.

Categories

Resources