2 Bootstrap Datepickers: How to change min and max dates? - javascript

I have 2 datepickers on my webpage: One for the arrival date and the other for departure.
Now I'd like to set the min and max dates, according to the user selection.
2 Examples of what I want to achieve:
User selects 29.03.2015 as arrival -> departure's min date is set
accordingly.
User selects 29.03.2015 as departure -> arrival's max
date is set accordingly.
At the moment I am initializing the datepickers like so:
var startDate = "<?php echo date('d.m.Y'); ?>"; // Today
$('#startDate.input-group.date').datepicker({
format: "dd.mm.yyyy",
language: "de",
multidate: false,
todayHighlight: true,
startDate: startDate,
weekStart: 1
}).on('changeDate', function(e){
changeDate(e);
});
$('#endDate.input-group.date').datepicker({
format: "dd.mm.yyyy",
language: "de",
multidate: false,
todayHighlight: true,
startDate: startDate,
weekStart: 1
});
You notice the .on() function on the first datepicker. This is my current attempt to set the date of the 2nd one:
function changeDate(e){
$('#endDate.input-group.date').datepicker('setStartDate', e);
}
However this leaves me with the following error:
Uncaught TypeError: undefined is not a function: bootstrap-datepicker.js:1493
The line in question is this:
parts = date.match(/([\-+]\d+)([dmwy])/g)
Can you please give me a hint on what I am doing wrong and on how I can achieve said effect?

if you console.log changing like this:
.on('changeDate', function(e){
console.log(e);
});
you'll see the event returns an event object;
you should try passing something like e.date (but be sure to format the string accordingly to your startDate format).
Here's more about the extra data attached to the event object : http://bootstrap-datepicker.readthedocs.org/en/latest/events.html

Related

Flatpickr second date equals to first selected date

We are using flatPickr with Wordpress plugin in our website. The problem is that plugin is made that dates would be selectable from first day till second day, but we need for user to be able to only select one day. So my idea was to add javascript so when user selects first day, second day would be automatically selected and equal to first selected day. I have added ID elements to both input fields and used this code as example:
Stackoverflow link
But nothing seems to be working
Javascript code example:
window.addEventListener("load", () => {
const first_date = document.getElementsByName('_dates[]')[0];
first_date.id = 'first_date';
const second_date = document.getElementsByName('_dates[]')[1];
second_date.id = 'second_date';
});
jQuery(document).ready(function ($) {
/*selecting datepiker language*/
flatpickr.localize(flatpickr.l10ns.en);
/*declaring return datepicker*/
var FLATPICKER_RITORNO = flatpickr('#second_date', {
altInput: true,
altFormat: "j F, Y",
dateFormat: "d-m-Y",
disableMobile: "true",
maxDate: new Date().fp_incr(365),
defaultDate: "today"
});
/*declaring outbound datepicker*/
$("#first_date").flatpickr({
altInput: true,
altFormat: "j F, Y",
dateFormat: "d-m-Y",
disableMobile: "true",
minDate: "today",
maxDate: new Date().fp_incr(365),
defaultDate: "today",
/* setting initial date of return picker to the one selected in
outbound*/
onChange: function (dateStr, dateObj) {
FLATPICKER_RITORNO.set("minDate", dateObj);
FLATPICKER_RITORNO.setDate(dateObj);
}
});
});
Link to the website
How it should work:
The date picker is in the main page of the website, when user clicks on "Datos" input field, flatpickr calendar appears. Now he is able to select multiple dates, but he should be able to select only first day and after selecting for example "September 1st" second date would be automatically selected as "September 1st" and the calendar would close.
Input field

Select only start date in Date Range and Set +7 days for End (Bootstrap Date Range Picker)

I am trying to have an event triggered when you click on the start date in the date range picker, I have tried a few ways and have this so far:
HTML:
<input class="form-control pull-right" type="text" name="daterange" id="dateRangeP" >
Javascript
$(function () {
$('input[name="daterange"]').daterangepicker({
locale: {
format: 'DD-MM-YYYY'
}
});
$('input[name="daterange"]').click(function () {
debugger;
var startDate = $("#dateRangeP").data('daterangepicker').startDate._d.toLocaleDateString('en-GB');
var endDate = moment(startDate, "DD-MM-YYYY").add(7, 'days')._d.toLocaleDateString('en-GB');
$("#dateRangeP").data('daterangepicker').setStartDate(startDate);
$("#dateRangeP").data('daterangepicker').setEndDate(endDate);
debugger;
$(this).val(startDate + '-' + endDate);
console.log($(this).val());
});
});
At the moment it works when you click outside the box but I need it for when I click on the start date. I have tried to use change the function to call below but it only works after the apply button is selected and both dates have been selected
$('#dateRangeP').on('apply.daterangepicker', function(ev, picker) {
alert ('hello');
});
I have done a lot of searching before posting here but cannot seem to find any guidance, some guidance would be greatly appreciated. If unclear please let me know.
Fiddle: http://jsfiddle.net/40cwdk7h/1/
Try this ...
dateLimit: { days: 7 }
$(function() {
$('input[name="daterange"]').daterangepicker({
dateLimit: { days: 7 },
locale: {
format: 'MM/DD/YYYY '
},
});
});
link https://jsfiddle.net/rLnycn80/1845/
Yes, that function is only called when you clicked on apply button.
For setting a dynamic end date at runtime used two datepicker instead of daterangepicker.
Fiddle Link: https://jsfiddle.net/kartik_bhalala/2euar7d3/19/

JQuery-UI Datepicker() click Done programmitally

Does anybody know how I can trigger the datepicker to fire its onClose() function as if the user made the selection and clicked the Done button?
Maybe I'm looking in the wrong place but I cannot seem to find a way to fire an event that mimics the user selecting the datepicker and clicking on the Done button.
Here's my scenario: I want the date to change when users select an option button. If the user selects the option "YEAR" then #StartDate changes to Jan 2016 and #EndDate changes to Dec 2016. If the user selects the option "MONTH" then #StartDate changes to Jan 2017 and #EndDate changes to Jan 2017.
There are max and min and other requirements handled in the initModule for both datepickers that only get executed when the user selects the datepickers, changes these dates, and clicks on the Done button. I want to fire these events without the user having to manually change the dates.
In my initModule method:
// ----------------Begin Public Methods----------------------------//
var initModule = function () {
var currYear = new Date().getFullYear();
// Hookup datepickers
$(#EndDate).datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
minDate: new Date(2013, 9, 1),
maxDate: '-1d',
beforeShow: function () {
setTimeout(function () {
$("#ui-datepicker-div").addClass('calendar-off');
}, 0);
},
onClose: function () {
var month = $(#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $(#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate' new Date(year, month, 1));
onChangeEndDate();
}
});
.
.
.
.
.
};
return { initModule: initModule };
So, I've tried $("#EndDate").click('onClose'); and $("#EndDate").trigger('onClose'); and I've poked around everywhere to find an answer to no avail.
How to I get execution into the onClose: function () without the user having to manually change the date in the datepicker and select the Done button?
According to the API documentation, the hide() method will close the datepicker.
So, if you want to close the datepicker, you should do
$(#EndDate).datepicker( "hide" );

Multiple datepicker using Pikaday

Im using Pikaday as a datepicker because JQuery Datepicker is having conflict with Prototype Library.
A few issues here.
How do i use pikaday datepicker in multiple text box
How to format the date. Previously by using JQuery Datepicker, to change the format I only need to
add dateFormat:"dd M yy",
Here is the sample code
<input type="text" id="datepicker">
<script src="pikaday.js"></script>
<script>
var picker = new Pikaday(
{
changeMonth: true,
changeYear: true,
field: document.getElementById('datepicker'),
firstDay: 1,
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
yearRange: [2000,2020]
});
</script>
I guess you're looking for a way to have pikaday work together for a date range type of thing and then manipulate the last one according to the date you selected in the first on?
...
I realize this is a bit late but perhaps someone else is interested in an answer:
Pikaday does not offer anything inhouse here but I was able to work around this by destroying the instance and creating it again when a day has been picked in the "from" picker.
HTML:
From: <input type="text" name="from" id="from">
To: <span id="toField"><input type="text" name="to" id="to"></span>
Javascript:
function dateRange() { //destroy to field and init with new param
var picker = new Pikaday({ field: document.getElementById("from") });
if(picker.toString()) {
$("#to").pikaday('destroy');
$("#to").remove();
$("#toField").html('<input type="text" name="to" id="to">');
$("#to").pikaday({ //should have the same param as the original init
format: "YYYY-M-DD",
minDate: moment(picker.toString(), "YYYY-MM-DD").toDate()
});
}
}
$(function() { //pikaday init
$("#from").pikaday({
format: "YYYY-MM-DD", //adjust to your liking
minDate: moment().subtract({days: 1}).toDate()
});
$("#to").pikaday({
format: "YYYY-MM-DD",
minDate: moment().subtract({days: 1}).toDate()
});
});
PS: don't forget to include your jquery, pickaday and moment js files...
Hope it helps
In case this stumps anyone else - you need to actually trigger the code in #Dominik's answer once a date has been selected, using the "onSelect" trigger. My code has ended up like this (because I'm using the jquery plugin version throughout in a UK format):
var dateFormat = "DD/MM/YYYY";
function dateRange() { //destroy to field and init with new param
var $from = $("#from").pikaday({
format: dateFormat,
});
if($from.val()) {
$("#to").pikaday('destroy');
$("#to").remove();
$("#toField").html('<input type="text" name="to" id="to">');
$("#to").pikaday({
format: dateFormat,
minDate: moment($from.val(), dateFormat).toDate()
});
}
}
$("#from").pikaday({
format: dateFormat,
minDate: moment().subtract({days: 1}).toDate(),
onSelect: dateRange
});
$("#to").pikaday({
format: dateFormat,
minDate: moment().subtract({days: 1}).toDate()
});
I realize this is not quite an answer to the op question, but if it's preferable to select a date range using one control, this is the method I'm using:
var cal = document.getElementById('datepicker');
var picker = new Pikaday({
onSelect: (function() {
var init = true,
start,
end;
return function(date) {
if (init) {
start = date;
picker.setStartRange(date);
picker.setEndRange(null);
rangeClear();
} else {
end = date;
picker.setEndRange(date);
rangeSet(start, end);
}
picker.draw();
init = !init;
}
}())
});
cal.appendChild(picker.el);
Where the rangeSet and rangeClear functions would exist elsewhere with the following signatures:
function rangeSet(start, end) {
//do something with the start and end dates
}
function rangeClear() {
//clear the start and end dates
}
You can see this working here: http://codepen.io/cshanejennings/pen/OMWLLg
The following is my Javascript (without jQuery) solution for From and To datepickers using Pikaday. It's working in Chrome and Firefox, but it does not work in Chrome-Android.
var nowDT = new Date();
var nowDTStr = nowDT.toShortDate();
var sin = document.createElement('input');
sin.setAttribute('type', 'text');
sin.setAttribute('id', this.id + "_cp_sin");
sin.style.width = '20%';
sin.style.cssFloat = 'left';
this.controlPanel.appendChild(sin);
this.sinPika = new Pikaday({
field: sin,
firstDay: 1,
minDate: new Date('2001-01-01'),
maxDate: new Date(nowDTStr),
yearRange: [2001, nowDT.getFullYear()]
});
this.sinPika.setDate(nowDTStr);
var ein = document.createElement('input');
ein.setAttribute('type', 'text');
ein.setAttribute('id', this.id + "_cp_ein");
ein.style.width = '20%';
ein.style.cssFloat = 'right';
this.controlPanel.appendChild(ein);
this.einPika = new Pikaday({
field: ein,
firstDay: 1,
minDate: new Date('2001-01-01'),
maxDate: new Date(nowDTStr),
yearRange: [2001, nowDT.getFullYear()]
});
this.einPika.setDate(nowDTStr);
Since I have sinPika and einPika objects added as members to my class, they're accessible elsewhere in my class in other methods, where Pika objects are used to fetch the dates set by users. Only thing is that this solution is not working in Chrome-Android for me. Could anyone try and let me know what you find?
Thanks!
Edit
I found the problem why Pikaday wasn't working on chrome-android for me. The reason is that the pikaday.js (https://github.com/dbushell/Pikaday/blob/master/pikaday.js) is different from the one here http://dbushell.github.io/Pikaday/, in that the difference lies in attaching the mousedown, touchend events. Pikaday.js on github attaches like this:
addEvent(self.el, 'ontouchend' in document ? 'ontouchend' : 'mousedown', self._onMouseDown, true);
(I think, Javascript defines touchend not ontouchend, may be, this is the reason why Pikaday.js from github repo does not work.)
And the one on dbushell.github.io/Pikaday attaches like this:
addEvent(self.el, 'mousedown', self._onMouseDown, true);
Using the script from http://dbushell.github.io/Pikaday/ works on chrome-android, the one on git repo does not.

How to get current viewMode property from "Bootstrap Datepicker"

How to get current viewMode property from "Bootstrap Datepicker"?
I initialize the control with viewMode= 'years' and I want to close datepicker on changeDate event, only when viewMode='days'.
The user selects a year, then a month, and finally a day. In that moment the control must be closed.
This is the code:
$("#date").datepicker(
{viewMode: 'years',
format: 'dd/mm/yyyy'
});
$('#date').on('changeDate', function (ev) {
//close when viewMode='0' (days)
})
Can anyone help?
Check this : http://jsfiddle.net/nAXnM/
HTML
<input type="text" class="span2" value="02/16/12" data-date-format="mm/dd/yy" id="dp2" >
JS
$("#dp2").datepicker({
viewMode: 'years',
format: 'dd/mm/yyyy'
});
$('#dp2').on('changeDate', function (ev) {
//close when viewMode='0' (days)
if(ev.viewMode === 'days'){
$('#dp2').datepicker('hide');
}
})
If you're using the forked version of Bootstrap Datepicker, to close the UI widget when a date is selected, set the autoclose option to true:
$("#date").datepicker({
autoclose: true
});

Categories