jQuery datepicker only works once and is not shown the second time
I had the same problem, and I solved with
$("#ui-datepicker-div").remove();
after closing and destroying the popup.
It is opened via an Ajax.ActionLink which updates a target id (div) via the UpdateTargetId property. The controller action returning the contents for the modal dialog queries a web service and then returns a partial view with a populated model.
then you need to call the datepciker function again after the partial view is populated... inside callback function of ajax(if you are using that)...
$.ajax({
success:function(){
//your stuff
$("#datepicker").datepicker();
}
});
datepikcker won't be able to call a function for dynamically added element... since your target div is not present at the time when the datepicker is first called... you need to call the datepicker function again for if to work for added target DIV
updated
OnSuccess = "openPopup()"
.....
function openPopup(){
//your codes
$("#datepicker").datepicker(); //call date picker function to the added element again
}
What worked for me was -
Inside the dialog, if I have multiple inputs with class datepicker
, then
$(".datepicker").removeClass('hasDatepicker').datepicker();
Basically, to remove the class hasDatepicker
before initializing datepicker
again.
I was on version 1.8.18 of jquery.ui.datepicker
After more debugging and attempts to trace jQuery events, I tested whether the problem existed with jQuery UI 1.9.2, which it didn't. Then I compared the relevant datepicker
code lines which did not involved too many actual changes.
To put a long story short, the problem described in my question above could be fixed by changing a single line of code back from 1.10.2 to what it was in 1.9.2:
1.10.2 causing problems
/* Initialise the date picker */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
1.9.2. version, working as expected
/* Initialise the date picker */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick)
// !!!!!!!!!!
// The next code line has to be added again so that the date picker
// shows up when the popup is opened more than once without reloading
// the "base" page.
// !!!!!!!!!!
.find(document.body).append($.datepicker.dpDiv);
$.datepicker.initialized = true;
}
I'm still not sure why this behaviour exists, but it seems to be a relatively rare constellation. As a note: I didn't "reinitialize" the datepicker
after opening the popup dialog (or requesting the PartialView
via AJAX), so having a single script source as part of the _Layout.cshtml
is sufficient. Hope this helps someone else.