loop available dates, select one of them and fill the input box - javascript

I am trying to fill in the input that is normally filled by a js code inside the html:
<input type="text" readonly="" class="form-control-input app_date validate" style="width: 260px;" id="app_date" name="app_date" placeholder="YYYY-MM-DD" onchange="this.form.submit();showLoader();" value="" autocomplete="off">
js code got from html
import re
html = """
<script type="text/javascript">
var dt4 = '2019-03-07';
var blocked_dates = ["20-03-2019","01-01-1970","28-03-2019","29-03-2019","20-03-2019","01-01-1970","28-03-2019","29-03-2019"];
var available_dates = ["07-03-2019","08-03-2019","11-03-2019","12-03-2019","13-03-2019","14-03-2019","15-03-2019","18-03-2019","19-03-2019","21-03-2019","22-03-2019","25-03-2019","26-03-2019","27-03-2019"];
var fullCapicity_dates = [];
var offDates_dates = ["09-03-2019","10-03-2019","16-03-2019","17-03-2019","20-03-2019","23-03-2019","24-03-2019","28-03-2019","29-03-2019","30-03-2019","31-03-2019"];
var allowArray = [1];
</script>
"""
i successfully captured the available dates :
date_list = re.findall(r'var\s*available_dates\s*=\s*\[[^\]]+', html)
if date_list:
for av_date in re.findall(r"\"[0-9\-]+\"",date_list[0]) :
print(av_date.replace('"',''))
Break
else : print("no available dates")
output :
07-03-2019 08-03-2019 11-03-2019 12-03-2019 13-03-2019 14-03-2019
15-03-2019 18-03-2019 19-03-2019 21-03-2019 22-03-2019 25-03-2019
26-03-2019 27-03-2019
I don't know how to loop the availables dates , select one of them and fill the input and continue the py script. if no available dates keep refreshing the current page until available dates are found. i am confused is it a while loop, a while true or if ?
full js code
<script type="text/javascript">
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = yyyy+'-'+mm+'-'+dd;
function formatDate(rawDate) {
var day = ("0" + rawDate.getDate()).slice(-2);
var month = ("0" + (rawDate.getMonth() + 1)).slice(-2);
return (day)+ "-" + (month)+ "-" +rawDate.getFullYear() ;
}
$(document).ready(function() {
var dt1 = '2019-03-06';
var checkService = 'Normal';
$('#dateOfBirth').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('#pptIssueDate').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('#pptExpiryDate').datepicker({
format: "yyyy-mm-dd",
startDate: new Date(dt1),
autoclose: true,
startView: 2
});
var dt4 = '2019-03-07';
var blocked_dates = ["20-03-2019","01-01-1970","28-03-2019","29-03-2019","20-03-2019","01-01-1970","28-03-2019","29-03-2019"];
var available_dates = ["07-03-2019","08-03-2019","11-03-2019","12-03-2019","13-03-2019","14-03-2019","15-03-2019","18-03-2019","19-03-2019","21-03-2019","22-03-2019","25-03-2019","26-03-2019","27-03-2019"];
var fullCapicity_dates = [];
var offDates_dates = ["09-03-2019","10-03-2019","16-03-2019","17-03-2019","20-03-2019","23-03-2019","24-03-2019","28-03-2019","29-03-2019","30-03-2019","31-03-2019"];
var allowArray = [1];
if(checkService == 'Normal')
{
/*if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1'))
{
var classFull = 'fullcapspecial';
var tooltipTitle = ' ';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}*/
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}
$('.app_date').datepicker({
language: "en",
Default: true,
format: "yyyy-mm-dd",
startDate: new Date(dt4),
endDate: '2019-03-31',
autoclose: true,
forceParse:true,
startView: 0,
beforeShowDay: function(date){
var formattedDate = formatDate(date);
if ($.inArray(formattedDate.toString(), blocked_dates) != -1){
return {
enabled : false,
classes: 'inactiveClass',
tooltip: 'Holiday'
};
}
if ($.inArray(formattedDate.toString(), available_dates) != -1){
return {
enabled : true,
classes: 'activeClass',
tooltip: 'Book'
};
}
if ($.inArray(formattedDate.toString(), fullCapicity_dates) != -1){
return {
enabled : false,
classes: classFull,
tooltip: tooltipTitle
};
}
if ($.inArray(formattedDate.toString(), offDates_dates) != -1){
return {
enabled : false,
classes: 'offday',
tooltip: 'Off Day'
};
}
return {
enabled : false,
tooltip: backDatetitle
};
return;
}
});
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
if(checkService == 'Normal')
{
if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1'))
{
/*$(document).on('click', '.fullcap,.fullcapspecial', function () {
$(".datepicker").hide();
$('.popupBG').show();
$('#IDBodyPanel').show();
});
$(".popupCloseIcon").click(function() {
$(".popupBG").hide();
$("#IDBodyPanel").hide();
});
$('input[type=radio][name=serviceChange]').change(function() {
if (this.value == 'Premium') {
$("#premiumService").prop('value', 'GO FOR PREMIUM');
}
else if (this.value == 'Prime') {
$("#premiumService").prop('value', 'GO FOR PRIME TIME');
}
});*/
}
}
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
var eventhandler = function(e) {
e.preventDefault();
}
if (checkService == 'Premium' || checkService == 'Prime') {
$('input[name="vasId[]"]:checked').each(function() {
$("#vasId"+this.value).bind('click', eventhandler);
});
}
if (checkService != 'Premium')
{
$(document).on('click', '.chkbox', function () {
if($(this).val() == 1)
{
if($(this).is(":checked")){
//$("#vasId6").prop('checked', true);
//$("#vasId6").bind('click', eventhandler);
}else{
//$("#vasId6").prop('checked', false);
//$("#vasId6").unbind('click', eventhandler);
}
}
});
}
});
</script>

Related

After choose time I get undefined

After I choose a time and submit a form, I get undefine
When I open console, there aren't any error.
$('.timepicker').timepicker({
timeFormat: 'h:mm p',
interval: 30,
minTime: '10',
maxTime: '3:00pm',
startTime: '10:00',
dynamic: true,
dropdown: true,
scrollbar: true
});
$(function () {
$("#datepicker").datepicker({
minDate: +1, maxDate: "+3M"
});
});
$(document).ready(function () {
var appointmentTime = document.getElementById('datepicker').value;
var splitData = "";
if (appointmentTime.indexOf("") > 0) {
splitData = appointmentTime.split(" ");
}
else {
splitData = appointmentTime.split("T");
}
var time = splitData[1].substring(0, 5);
if (time.slice(-1) == ":") {
time = time.substring(0, time.length - 1);
}
var amPmTime = splitData[2];
$('#datepicker').attr('value', splitData[0]);
$('#timepicker').attr('value', time + ' ' + amPmTime);
});
And in my field I get something like this:
Image
Any idea what could be problem ?

ui-datepicker-div is empty in angular directive

I am using ui-datepicker and it is working fine on chrome but not on safari. I have also tried by putting CSS file first and then JS file in my main index.html file. It is generating ui-datepicker-div in bottom but it is empty on Safari.
Here is HTML i am using:
<input type="image" src="images/calendar-icon.jpg" ng-model="selectedWeek" weekpicker format="yy-mm-dd" style="margin-left:10px;" />
and here is JavaScript i am using:
myApp.directive('weekpicker', function () {
function link(scope, element, attrs, ngModelCtrl, $rootScope) {
var frmt = "mm/dd/yy";
if (attrs.format != undefined) {
frmt = attrs.format;
} else if (attrs.placeholder != undefined) {
frmt = attrs.placeholder;
}
scope.getSunday = function(fromDate) {
var curr = new Date(fromDate); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var firstday = new Date(curr.setDate(first)).toUTCString();
return firstday;
};
scope.getWeekDaysRange = function (inputDateString) {
return scope.getDates(new Date(inputDateString), (new Date(inputDateString)).addDays(6));
};
scope.getDates = function(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
var curdate = new Date(currentDate);
var dateElements = {
day : cal_days_labels[curdate.getDay()],
date : curdate.getDate(),
month : cal_months_labels[curdate.getMonth()],
year : curdate.getFullYear(),
datestamp : curdate.getFullYear()+''+scope.padWithZero(curdate.getMonth()+1)+''+scope.padWithZero(curdate.getDate())
};
dateArray.push(dateElements);
currentDate = currentDate.addDays(1);
}
return dateArray;
};
scope.padWithZero = function(number) {
if(number>-10 && number<10) {
number = '0'+number;
}
return number;
};
$(element).datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showWeek: true,
beforeShow: function(dateText, inst) {
},
onSelect : function(dateText, inst) {
current = {day: inst.currentDay, month : inst.currentMonth, year : inst.currentYear};
var selectedDateString = new Date(current.year+'-' + (1+current.month) + '-' + current.day);
var weekBoundryDates = selectedDateString.getWeekBoundryDaysFromToday();
var weekBoundries = weekString(weekBoundryDates);
scope.$apply(function() {
scope.selectedWeek = weekBoundries;
});
scope.$digest();
scope.$emit("weekselected", inst);
},
onClose: function(dateText, inst) {
}
});
scope.$watch(function(scope){
return scope.selectedWeek;
}, function(newVal, oldVal){
});
};
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
the above code is working fine in Chrome, but not in Safari.
Can anyone help me please.
Change input type image to text it will work :)
<input type="text" src="images/calendar-icon.jpg" ng-model="selectedWeek" weekpicker format="yy-mm-dd" style="margin-left:10px;" />

Custom function be called instead of getfullyear() in java script

I want my custom function be called instead of getfullyear() in java script how can I do this ? The point is to change a gregorian calendar to jallali in jomsocial.
for example when I write this
d=new Date(b.year,b.month,b.date+a);c.set("highlight",JalaliDate[d.getFullYear(),d.getMonth(),d.getDate()]
The result will be 2014/16/7, I want it to became 1393/6/25
This is the function that I want to be called
http://www.farsiweb.info/jalali/jalali.js
or
jQuery(function($){
$.datepicker.regional['fa'] = {
calendar: JalaliDate,
closeText: 'بستن',
prevText: 'قبل',
nextText: 'بعد',
currentText: 'امروز',
monthNames: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
monthNamesShort: ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],
dayNames: ['یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
dayNamesShort: ['یک', 'دو', 'سه', 'چهار', 'پنج', 'جمعه', 'شنبه'],
dayNamesMin: ['ی','د','س','چ','پ','ج','ش'],
weekHeader: 'ه',
dateFormat: 'dd/mm/yy',
firstDay: 6,
isRTL: true,
showMonthAfterYear: false,
yearSuffix: '',
calculateWeek: function(date) {
var checkDate = new JalaliDate(date.getFullYear(), date.getMonth(), date.getDate() + (date.getDay() || 7) - 3);
return Math.floor(Math.round((checkDate.getTime() - new JalaliDate(checkDate.getFullYear(), 0, 1).getTime()) / 86400000) / 7) + 1;
}};
$.datepicker.setDefaults($.datepicker.regional['fa']); });
function JalaliDate(p0, p1, p2) {
var gregorianDate;
var jalaliDate;
if (!isNaN(parseInt(p0)) && !isNaN(parseInt(p1)) && !isNaN(parseInt(p2))) {
var g = jalali_to_gregorian([parseInt(p0, 10), parseInt(p1, 10), parseInt(p2, 10)]);
setFullDate(new Date(g[0], g[1], g[2]));
} else {
setFullDate(p0);
}
function jalali_to_gregorian(d) {
var adjustDay = 0;
if(d[1]<0){
adjustDay = leap_persian(d[0]-1)? 30: 29;
d[1]++;
}
var gregorian = jd_to_gregorian(persian_to_jd(d[0], d[1] + 1, d[2])-adjustDay);
gregorian[1]--;
return gregorian;
}
function gregorian_to_jalali(d) {
var jalali = jd_to_persian(gregorian_to_jd(d[0], d[1] + 1, d[2]));
jalali[1]--;
return jalali;
}
function setFullDate(date) {
if (date && date.getGregorianDate) date = date.getGregorianDate();
gregorianDate = new Date(date);
gregorianDate.setHours(gregorianDate.getHours() > 12 ? gregorianDate.getHours() + 2 : 0)
if (!gregorianDate || gregorianDate == 'Invalid Date' || isNaN(gregorianDate || !gregorianDate.getDate())) {
gregorianDate = new Date();
}
jalaliDate = gregorian_to_jalali([
gregorianDate.getFullYear(),
gregorianDate.getMonth(),
gregorianDate.getDate()]);
return this;
}
this.getGregorianDate = function() { return gregorianDate; }
this.setFullDate = setFullDate;
this.setMonth = function(e) {
jalaliDate[1] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
}
this.setDate = function(e) {
jalaliDate[2] = e;
var g = jalali_to_gregorian(jalaliDate);
gregorianDate = new Date(g[0], g[1], g[2]);
jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
};
this.getFullYear = function() { return jalaliDate[0]; };
this.getMonth = function() { return jalaliDate[1]; };
this.getDate = function() { return jalaliDate[2]; };
this.toString = function() { return jalaliDate.join(',').toString(); };
this.getDay = function() { return gregorianDate.getDay(); };
this.getHours = function() { return gregorianDate.getHours(); };
this.getMinutes = function() { return gregorianDate.getMinutes(); };
this.getSeconds = function() { return gregorianDate.getSeconds(); };
this.getTime = function() { return gregorianDate.getTime(); };
this.getTimeZoneOffset = function() { return gregorianDate.getTimeZoneOffset(); };
this.getYear = function() { return jalaliDate[0] % 100; };
this.setHours = function(e) { gregorianDate.setHours(e) };
this.setMinutes = function(e) { gregorianDate.setMinutes(e) };
this.setSeconds = function(e) { gregorianDate.setSeconds(e) };
this.setMilliseconds = function(e) { gregorianDate.setMilliseconds(e) }; }
Thanks
If you are using http://www.farsiweb.info/jalali/jalali.js, try
function printJalali(year, month, day) {
var jalali = gregorian_to_jalali([year, month+1, day]);
return jalali[0] + "/" + jalali[1] + "/" + jalali[2];
}
var today = new Date();
alert(printJalali(today.getFullYear(), today.getMonth(), today.getDate()));

datetimepicker update mindate maxdate

I am using jquery datetimepicker for two textboxes From date To date. I want to update the values mindate and maxdate from the other text box. The first time it is working fine but if I change the values on debug are correct but the datetimepicker doesnt update. My question is how I will make datetimepicker to update. Reading the code I think it is more clear. Thank you
$(".DatePickerFieldOnHire").live('click', function () {
var defaultDateTime = "";
var dateFrom = "";
var dateTo = "";
dateFrom = document.getElementById('WebReportForm1_Value_DeliveryDate').value;
dateTo = document.getElementById('WebReportForm1_Value_ExpectedRedeliveryDate').value;
var now = new Date();
var dateNow=now.format("dd-mm-yy HH:mm z");
dateFrom = document.getElementById('WebReportForm1_Value_DeliveryDate').value;
dateTo = document.getElementById('WebReportForm1_Value_ExpectedRedeliveryDate').value;
var now = new Date();
var dateNow=now.format("dd-mm-yy HH:mm z");
if (dateFrom == null) {
dateFrom = new Date(1999, 10 - 1, 25);
}
if (dateTo == null) {
dateTo = new Date(2055, 10 - 1, 25);
defaultDateTime = dateNow;
} else {
if (dateTo > dateNow) {
defaultDateTime = dateNow;
}
else {
defaultDateTime = dateTo;
}
}
var inputOff = "";
inputOff = $('[id*="OffHireDateField"]').val();
if (inputOff != "") {
dateFrom = inputOff;
}
$(this).datetimepicker({
showOn: 'focus', showTimezone: false, ampm: true, dateFormat: "dd-mm-yy",
timeFormat: "HH:mm z",
minDate: dateFrom,
maxDate: dateTo,
showTimezone: true,
defaultDate: defaultDateTime,
onSelect: function () { }
}).focus();
});
and the From textbox
$(".DatePickerFieldOffHire").live('click', function () {
var dateFrom = "";
var dateTo = "";
dateFrom = document.getElementById('WebReportForm1_Value_DeliveryDate').value;
dateTo = document.getElementById('WebReportForm1_Value_ExpectedRedeliveryDate').value;
if (dateFrom == null) {
dateFrom = new Date(1999, 10 - 1, 25);
}
if (dateTo == null) {
dateTo = new Date(2055, 10 - 1, 25);
defaultDateTime = dateNow;
} else {
if (dateTo > dateNow) {
defaultDateTime = dateNow;
}
else {
defaultDateTime = dateTo;
}
}
var inputOn = "";
inputOn = $('[id*="OnHireDateField"]').val();
if (inputOn != "") {
dateTo = inputOn;
}
$(this).datetimepicker({
showOn: 'focus', showTimezone: false, ampm: true, dateFormat: "dd-mm-yy",
timeFormat: "HH:mm z",
minDate: dateFrom,
maxDate: dateTo,
showTimezone: true,
defaultDate: defaultDateTime,
onSelect: function () { }
}).focus();
});
I have to admit, I did not check the code thoroughly as you have not included a JSFiddle, but from what I can see, it looks like the first time, dateFrom and dateTo are Date objects but from the second time on they are Strings.
This might be an issue.
Your date format dd-mm-yy does not comply with the default format yy-mm-dd.

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

Categories

Resources