问题
I have a datepicker with an onClose function that is called when user select a date (correct), but also when the calendar is shown but user clicks anywhere in the document (wrong).
Inside onClick, is there a way to distinguish between user's click on a date (then calendar is closed) and user's click in the document?
$( "#datePicker" ).datepicker({
...
onClose: myFunction(),
...
});
The same calendar is used in 2 ways:
- sometimes user can select a day (click on a day -> myFunction() must be called)
- sometimes user must select a month (select month -> click 'ok' button -> myFunction() must be called)
I tried use 'onSelect': it works only when user clicks on a day, but myFunction isn't called when calendar is "select month mode"
thanks.
This is the code I tried with @Prashant Kumar solution:
my={};
(function(){
my.customCalendar={
closedBySelect:false,
init: function()
{
$( "#datePicker" ).datepicker({
...
onSelect: function () {
my.customCalendar.myFunction();
this.closedBySelect = true;
},
onClose: function (){
console.log('fired on close');
if (this.closedBySelect) {
console.log('logic when closed on select');
this.myFunction();
} else {
console.log('logic when closed on document click');
}
my.customCalendar.closedBySelect = false;
},
...
showButtonPanel: true
});
...
myFunction:function (dateText, inst)
{
...
},
...
}
回答1:
How about this
$(function () {
$('#datepicker').datepicker({
closedBySelect:false,
onSelect: function (date, options) {
alert('fired when selected');
options.settings.closedBySelect = true;
},
onClose: function (date, options) {
alert('fired on close');
if (options.settings.closedBySelect) {
console.log('logic when closed on select');
} else {
console.log('logic when closed on document click');
}
options.settings.closedBySelect = false;
}
});
});
closedBySelect is not in the API rather it is a custom attribute added which we can easily be set in all events of datepicker :)
Update Code :
Used slightly different approach here -
$(function () {
var datePicker = $('#datepicker');
datePicker.data('closedOn','document').datepicker({
showButtonPanel:true,
onClose: function (date, options) {
alert($(this).data('closedOn'));
// your logic goes here ...
$(this).data('closedOn','document');
}
}).datepicker('widget').on('mousedown',function(event){
var $this = $(this);
var target = $(event.target);
if(target.hasClass('ui-datepicker-close'))
{
console.log('closed from button panel');
datePicker.data('closedOn','byButtonPanel');
}
if( typeof target.parent().data('month') != 'undefined')
{
console.log('closed by selecting date');
datePicker.data('closedOn','byDateSelect');
}
});
});
来源:https://stackoverflow.com/questions/27703745/jquery-ui-datepicker-onclose-distinguish-between-date-click-and-document-click