using the latest version of Daterangepicker for bootstrap
For the following calendar (standard example used in their website):
$('#demo').daterangepicker({
"singleDatePicker": true,
"autoApply": true,
"startDate": "05/31/2017",
"endDate": "06/06/2017"
}, function(start, end, label) {
console.log("a date is selected")
});
The given callback function is called correctly when I select a date in my calendar. However, if I select the active date which is already selected, the pop up is closed but the callback function is not called. As far as I see, there is no any opportunity provided to fire a function when the same date is selected.
So, my question would be: Is there a hacking way to have a callback function which is called when the same date is selected?
For instance, I tried the following piece of code to add a listener to the active cell but it is also not fired:
$('td.active.start-date.active.end-date.available').on('click', function () {
console.log('the same date is selected')
})
What you can do is bind an extra event to your input which will be called when you select an option. See the following code (assuming the element with id demo is your input) Since you already use jQuery my example uses this as well:
$('#demo').on('change.datepicker', function(ev){
var picker = $(ev.target).data('daterangepicker');
console.log(picker.startDate); // contains the selected start date
console.log(picker.endDate); // contains the selected end date
// ... here you can compare the dates and call your callback.
});
Hope this will help!
The 'click' event does not work, but the 'mousedown' event does.
Below an example, which identifies the clicked element ('td.available') and programatically clicks the same date again.
$('#demo').on('showCalendar.daterangepicker', function(ev, picker) {
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
// when user selects ("mousedown") any date in the calendar:
$('td.available').on("mousedown", function() {
clickedElement = $('td.in-range')[0]; // this is the clicked element
// example: programatically click again.
triggerMouseEvent (clickedElement, "mouseover");
triggerMouseEvent (clickedElement, "mousedown");
triggerMouseEvent (clickedElement, "mouseup");
triggerMouseEvent (clickedElement, "click");
);
});
});
Related
I have some flatpickr calendars with day and time, and I want to close the calender when I double click on a flatpickr-day element in the calendar.
I tried to add a double click listener in the flatpickr options, the onOpen field
var flatpckr_options = {
enableTime: true,
altInput: true,
altFormat: "d-m-Y H:i",
dateFormat: "Y-m-d H:i",
time_24hr: true,
allowInput: true,
onOpen: function(selectedDates, dateStr, instance) {
[...instance.calendarContainer.querySelectorAll(".flatpickr-day")].map(x => x.addEventListener('dblclick', function (e) {
calendars.map(x => x.close());
console.log("double click");
}));
}
};
const calendars = flatpickr(".calendar", flatpckr_options);
https://jsfiddle.net/p3e0da6r/2/
however the double click event doesn't get triggered on the flatpickr-day element, how can I get it to work?
I think it's because once I click on a day it changes focus to the flatpickr-time element, if I didn't have the time element the calendar would close on single click inside a flatpickr-day element by default, but I do need the time element as well.
There are many issues with your code -
First of all your input is a normal input, you need to add the attribute data-input so that your flatpickr work.
<input type='text' id='date' class='calendar' data-input/>
In the onOpen function - [...instance.calendarContainer.querySelectorAll("flatpickr-day")], flatpickr-day is a class and not a standalone element. You can select by .flatpickr-day.
[...instance.calendarContainer.querySelectorAll(".flatpickr-day")]
You need to use the event of https://flatpickr.js.org/events/, instead of dblclick use onChange.
Here is the working fiddle - https://jsfiddle.net/mkwa9bhv/
Note - variables declared with const are not hoisted. Declare const calendars = flatpickr(".calendar", flatpckr_options); at the top, so that it will be available within your flatpckr_options.
A less than perfect solution, but gets the job done for what I need right now:
var new_date = 0, old_date = 0;
// ... inside the flatpickr options, for the onChange event
onChange: function(selectedDates, dateStr, instance) {
old_date = new Date();
[...instance.calendarContainer.querySelectorAll(".flatpickr-day")].map(x => x.addEventListener('mousedown', function (e) {
new_date = new Date();
let diff = new_date - old_date; // in ms < 500ms => double click
if (diff <= 500) {
calendars.map(y => y.close());
}
old_date = new_date;
}));
},
I'm using fullcalendar for my calendar functionality. I'm using dayClick and select. In fullcalendar, select will be called even though it is a single day click. So, I changed the dayClick event like below to handle the day click. Here is my code
dayClick: function(date, jsEvent, view) {
isClicked = true;
},
select: function(startDate, endDate){
if(isClicked){
console.log('click');
return;
}
var start_date = moment(startDate).format('Y-MM-DD');
var end_date = moment(endDate).format('Y-MM-DD');
if(start_date != end_date){
end_date = moment(endDate).subtract(1, 'days').format('Y-MM-DD');
}
var set_default_duration = isClicked == true ? true : false ;
isClicked = false;
var user = $(t).attr('data-code');
// Some other stuff
},
Actually, I want to handle double click to create new events. I tried with dblclick event function from jquery with the calendar but always single click only triggers. The problem is, immediately after the click made, select is fired, so I'm unable to handle the double click. Can someone help me to handle the double click in this case.
Here is the Fiddle
EDIT: I'm trying to handle double click of the empty slots to create new event. Currently, single click is doing this
I found the answer. The problem is with the selection. It is selected once the day is clicked. So, I used unselect method to clear the selection and it seems fine now. Here is the code
dayClick: function(date, jsEvent, view) {
if(isClicked){
isDblClicked = true;
isClicked = false;
}
else{
isClicked = true;
}
setTimeout(function(){
isClicked = false;
}, 250);
},
select: function(startDate, endDate, jsEvent){
if(isClicked){
$(t).fullCalendar('unselect');
return;
}
// Other stuff
}
Well you could assign a new variable thats called clickedTimes or something like that and set it to zero.
Whenever you get a click you set clickedTimes to one and then two and you check if clickedTimes is at 2.
When it gets to two let it do the thing you want and set it back to zero.
I am trying to make function call on bootstrap datepicker when user clicks outside of calendar.
When user selects date datepicker closes automatically, same when user clicks outside of the datepicker div, it closes itself.
So my question is how can I understand when its closed? I know there is an event called onClose but it only works when page loads
fiddle
Use the .on("hide"... event.
From the docs:
$('.datepicker').datepicker()
.on(picker_event, function(e) {
// `e` here contains the extra attributes
});
For your example... picker_event will be hide.
Something like:
var checkin = $('#date-from').datepicker({
format: 'dd/mm/yyyy',
startDate: '+1d',
weekStart: 1,
beforeShowDay: function(date) {
return date.valueOf() >= now.valueOf();
},
autoclose: true
}).on('changeDate', function(ev) {
alert("changed");
}).on('hide', function(ev) { // <-----------
alert("hide");
});
Updated fiddle
bootstrap-datepicker events
bootstrap-datepicker hide event
As per the documentation here: https://bootstrap-datepicker.readthedocs.io/en/latest/events.html#hide
$('.datepicker').datepicker()
.on('hide', function(e) {
// `e` here contains the extra attributes
});
Or
$('.datepicker').datepicker()
.on('hide', myFunction);
And then create myFunction
function myFunction(e) {
// whatever you want :)
}
Here is your example with little modify https://jsfiddle.net/mr3dxj5p/6/ here you can see I just change changeDate to hide to fire alert message
In a codebase I'm working on there's this type of callback binding where something has to happen whenever any input gets changed
$(document.body).on('change', '.input-sm', function (){
...
})
The thing is, some input-sms are changed via a clockpicker, which does not trigger the 'change' event. How would I make this work? Ideally, I'd like clockpicker to trigger the change event.
http://jsfiddle.net/4zg3w5sj/7/
EDIT: A callback is being bound to multiple inputs with clockpickers at once, so I can't use the input variable to trigger the change event (except if I explicitly iterate over the inputs I guess)
you can use the clockpicker callbacks
beforeHourSelect : callback function triggered before user makes an
hour selection
afterHourSelect : callback function triggered after user makes an
hour selection
beforeDone : callback function triggered before time is written to
input
afterDone : callback function triggered after time is written to input
input.clockpicker({
autoclose: true,
afterDone: function() {
input.trigger("change");
}
});
I've figure out the issue
The plugin trigger the change event but they use triggerHandler instead of trigger that mean you can't add listener on body , you have to listen directly on the input
// Hours and minutes are selected
ClockPicker.prototype.done = function() {
raiseCallback(this.options.beforeDone);
this.hide();
var last = this.input.prop('value'),
value = leadingZero(this.hours) + ':' + leadingZero(this.minutes);
if (this.options.twelvehour) {
value = value + this.amOrPm;
}
this.input.prop('value', value);
if (value !== last) {
this.input.triggerHandler('change');
if (! this.isInput) {
this.element.trigger('change');
}
}
if (this.options.autoclose) {
this.input.trigger('blur');
}
raiseCallback(this.options.afterDone);
};
see here a fix
var input = $('#input-a');
var value = input.val();
// bind multiple inputs
$('.myinput').clockpicker({
autoclose: true,
afterDone: function() {
console.log("test");
}
});
// in the actual code it's not tied to an id but to a non-unique class
// does not trigger if changed by clock-picker
$(".myinput").on('change', function(){
console.log("!!!!")
})
<script type="text/javascript">
// When the document is ready
$(document).ready(function () {
$('.datepicker').datepicker({
format: "yyyy-mm-dd",
}).on('changeDate', function(ev){
// do what you want here
$(this).datepicker('hide');
}).on('changeDate', function(ev){
if ($('#startdate').val() != '' && $('#enddate').val() != ''){
$('#period').text(diffInDays() + ' d.');
} else {
$('#period').text("-");
}
});
});
</script>
So here's what my datepicker looks like. So basically when I change date by clicking mouse it works good, however when I manually change date with keyboard or manually clear the date change date event doesn't get called. Is this a bug or am I doing something wrong here ?
You have to use the change event on the input itself if you want to respond to manual input, because the changeDate event is only for when the date is changed using the datepicker.
Try something like this:
$(document).ready(function() {
$('.datepicker').datepicker({
format: "yyyy-mm-dd",
})
//Listen for the change even on the input
.change(dateChanged)
.on('changeDate', dateChanged);
});
function dateChanged(ev) {
$(this).datepicker('hide');
if ($('#startdate').val() != '' && $('#enddate').val() != '') {
$('#period').text(diffInDays() + ' d.');
} else {
$('#period').text("-");
}
}
In version 2.1.5
bootstrap-datetimepicker.js
http://www.eyecon.ro/bootstrap-datepicker
Contributions:
Andrew Rowls
Thiago de Arruda
updated for Bootstrap v3 by Jonathan Peterson #Eonasdan
changeDate has been renamed to change.dp so changedate was not working for me
$("#datetimepicker").datetimepicker().on('change.dp', function (e) {
FillDate(new Date());
});
also needed to change css class from datepicker to datepicker-input
<div id='datetimepicker' class='datepicker-input input-group controls'>
<input id='txtStartDate' class='form-control' placeholder='Select datepicker' data-rule-required='true' data-format='MM-DD-YYYY' type='text' />
<span class='input-group-addon'>
<span class='icon-calendar' data-time-icon='icon-time' data-date-icon='icon-calendar'></span>
</span>
</div>
Date formate also works in capitals like this data-format='MM-DD-YYYY'
it might be helpful for someone it gave me really hard time :)
The new version has changed.. for the latest version use the code below:
$('#UpToDate').datetimepicker({
format:'MMMM DD, YYYY',
maxDate:moment(),
defaultDate:moment()
}).on('dp.change',function(e){
console.log(e);
});
Try this:
$(".datepicker").on("dp.change", function(e) {
alert('hey');
});
I found a short solution for it.
No extra code is needed just trigger the changeDate event. E.g.
$('.datepicker').datepicker().trigger('changeDate');
Try with below code sample.it is working for me
var date_input_field = $('input[name="date"]');
date_input_field .datepicker({
dateFormat: '/dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
}).on('change', function(selected){
alert("startDate..."+selected.timeStamp);
});
This should make it work in both cases
function onDateChange() {
// Do something here
}
$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);
Depending which date picker for Bootstrap you're using, this is a known bug currently with this one:
Code: https://github.com/uxsolutions/bootstrap-datepicker
(Docs: https://bootstrap-datepicker.readthedocs.io/en/latest/)
Here's a bug report:
https://github.com/uxsolutions/bootstrap-datepicker/issues/1957
If anyone has a solution/workaround for this one, would be great if you'd include it.
I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does
I figure out like this
document.getElementById('date').onchange = function(){ ...the jquery code...}
I hope work for you
I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:
$(form).on('change change.dp dp.change changeDate' function () {...})
And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:
// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {
$('input[bs-datepicker]').on('focus', function (e){
e.currentTarget.focusValue = e.currentTarget.value;
});
$('input[bs-datepicker]').on('blur', function (e){
if (e.currentTarget.focusValue !== e.currentTarget.value) {
var event = new Event('change', { bubbles: true });
e.currentTarget.dispatchEvent(event);
}
});
})
This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.
Hope this helps someone!
if($('.single_datetime').length){
$('.single_datetime').dateRangePicker({ format: 'DD.MM.YYYY HH:mm', language: 'tr', autoClose: true, singleDate : true, showShortcuts: false, time: {enabled: true}
}).bind('datepicker-change',function(event,obj){caclDay();});
}
Ref: https://www.chamonix-property.com/bower_components/jquery-date-range-picker/