Alex Hakkenberg Alex Hakkenberg - 3 months ago 24
jQuery Question

AJAX loaded JQuery datepicker only working after alert

I got a pretty odd question.
I created a field with a datepicker assigned.

This field is being loaded by an AJAX call into a div.

In summarry this is working already.. But there's a catch.
It only works if I set an alert code before I initiate the datepicker.

When I remove the alert. It simply stops working.

The init code is within another function:

alert('kut');
$("#mini_calendar").datepicker({
defaultDate: "now",
constrainInput: false,
changeMonth: true,
numberOfMonths: 2,
onClose: function (selectedDate) {
}
});


I hope someone knows what I am doing wrong.

EDIT

Thanks a million.

The solution is :

interval = setInterval(function(){
if($("#mini_calendar").length > 0) {
$("#mini_calendar").datepicker({
defaultDate: "now",
constrainInput: false,
changeMonth: true,
numberOfMonths: 2,
onClose: function (selectedDate) {
}
});
clearInterval( interval );
}
}, 300);


Edit:

I am calling these on Ajax success :

///######## IN CASE OF SUCCESS
success: function (response) {
if (response != '') {
$("[@targetDiv]").html(response);
DateNav_CalendarInit(DisplayType);
}
else {
alert('error! Something went wrong during the obtaining of data!');
}
}


The "DateNav_CalendarInit()" calls the initialisation code

Answer

Without the alert you are trying to capture DOM element before it actually exists.

You should wait for the Document Ready event:

Example:

$(function(){
    // .. your code here ..
}

...or simply put your javascript code at the bottom of the tag (or at least after *#mini_calendar" element).

Comments