11

ASP.NET MVC3 / jQuery 1.9.1 / jQuery UI 1.10.2

I've got a page on which I open a modal dialog after clicking on an Ajax.ActionLink. Inside this dialog I have an input field and a datepicker associated with it. When I open the dialog for the first time, I can click on the datepicker button (or inside the associated input field so it receives focus, showOn is set to both), and the datepicker shows as expected. I can, while the modal dialog is open, do it as often as I want to, the datepicker shows every time. When I close the modal dialog (via an attached $("ui-widget-overlay").click(function(){...}); and then open it again, the datepicker no longer works, no matter whether I try to click on the button or into the associated input field.

I tried to debug the jQuery code, and both times the lines of code being run are the same (and even though the datepicker doesn't show up the second time the dialog is opened, the jQuery methods are triggered) from what I can see in the debugger. I'm completely stumped, and the methods described in this post only helped in terms of being to show the datepicker the first time the dialog opens. Another post only seems to be related to a misunderstanding how the showOn setting works.

I also tried to destroy the datepicker via $("#datepicker").datepicker("destroy"); when closing the dialog - to no avail. Any ideas?

Update

On the "calling page":

$(document).ready(function () {
    $("#popupDialog").dialog(
    {
        autoOpen: false,
        modal: true,
        open: function()
        {
            $("ui-widget-overlay").click(function()
            {
                $("#popupDialog").dialog("close");
            }
        }
    });
});
[...]
@Ajax.ActionLink( "Some text", "Action", "Controller", new AjaxOptions {
    HttpMethod = "GET",
    UpdateTargetId = "popupDialog",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "openPopup()"
})
[...]
function openPopup()
{
    $("popupDialog").dialog("open");
}
[...]
<div id="popupDialog" style="display: none;"></div>

The controller action is very simple and as follows:

public ActionResult Action()
{
    MyActionModel myActionModel = new MyActionModel();
    return PartialView( myActionModel );
}
4
  • is the content inside the model is added dynamically ??
    – bipen
    Commented Apr 18, 2013 at 6:52
  • Do you mean the content of the modal dialog? 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. Commented Apr 18, 2013 at 6:55
  • Can you show the html+js code ?
    – LeGEC
    Commented Apr 18, 2013 at 6:59
  • yes... i updated my answer.. check it out
    – bipen
    Commented Apr 18, 2013 at 7:02

10 Answers 10

23

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.

2
  • Works for 1.10.4 also. This was a lifesaver. You saved me (and my company) a lot of hours here.
    – jumps4fun
    Commented Mar 17, 2014 at 16:08
  • Tip for those of you using the minimised version of the JQuery UI script, simply chain the find/append to your .datepicker(); i.e. $('#dateField').datepicker({options}).find(document.body).append($.datepicker.dpDiv); - this worked for me on version 1.11.4 Commented Sep 17, 2015 at 12:27
15

I had the same problem, and I solved with

$("#ui-datepicker-div").remove();

after closing and destroying the popup.

1
  • Confirming it still works. You do initialize the datepicker in the ajax loaded file and in the file calling this ajax (from a button in my case), you remove the div as explained. Here is an example code to use (Bootstrap 4 modal): $('#modal1').on('hidden.bs.modal', function () { $("#ui-datepicker-div").remove(); $(this).find('.modal-content .modal-body').html(''); });
    – WeidMaster
    Commented Sep 8, 2020 at 20:44
6

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

2
  • i though this would fix my issue but it didnt. so im still bummed.
    – Brobina
    Commented Oct 30, 2014 at 15:31
  • $("#datepicker").removeClass('hasDatepicker') upon closing the dialog window fixed it for me, thanks for the tip!
    – jones
    Commented Mar 14, 2017 at 11:18
2

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
}
5
  • Where exactly would I have to put that code? I tried to add it to the OnSucces (I updated my question above) as in: OnSuccess = "openPopup();$('#datepicker').datepicker();" but that doesn't work. Commented Apr 18, 2013 at 7:03
  • @Gorgsenegger openPopup() is the function that you are calling on succes rite ?? call datepicker inside that function
    – bipen
    Commented Apr 18, 2013 at 7:10
  • Sorry for the delayed reply, yes, that's correct. I tried adding the code so the openPopup method is now like: $("#popupDialog").dialog("open");$("#datepicker").datepicker();. Unfortunately this didn't change anything. As said above (and that's what I don't get): It does work the first time I open the popup, and even then the data is retrieved from the webservice and returned as a PartialView. Debugging the button click for the datepicker shows in both cases the same lines being called, but after the first time the dialog was opened the datepicker won't show up anymore. Commented Apr 18, 2013 at 13:01
  • Same result. Added it before $("ui-widget-overlay").click(function().... I really don't get it, especially because I compared both replies (including all scripts etc) from the server via Fiddler, and both look, apart from time stamps, exactly the same. Commented Apr 18, 2013 at 13:08
  • Found the solution, although I don't understand why the problems described above are caused by the omission of the find(document.body).append($.datepicker.dpDiv). As I said - it only stops working (with the original 1.10.2 version) when I open the popup more than once without reloading the base page. Thanks anyway for your help. Commented Apr 22, 2013 at 14:19
2

I had a similar problem, but what happened to me was that the second time the dialog was loaded, the datapicker didn´t take the value.

The problem was that I was loading a second time the dialog and these cause problems. The solution was to remove the dialog after close it, something like:

  $("#popupDialog").dialog("close");    
  $("#popupDialog").remove();

I hope this helps anyone!

1

You can do this by adding a new function to div onclick="focusBlur()"

<script>
    function focusBlur() {
        $('input').blur();
    }
</script>
0

I wanted to re-inititalise the date picker after modal close as the values selected during the first trial for setting of the dates were still there. So i dont know why but the following code doesnt work for me.

$(selector).datepicker("refresh") 

The above line mentioned in the documentation didnt help!.

Following is something which i tried, i.e to destroy and reinititalise the date picker objects.

$('#addPromoModal').on('hide.bs.modal', function(event) {
$("#startDate").datepicker("destroy");
$("endDate").datepicker("destroy");
initialiseDataPicker(); }

Here is my initialise function :

function initialiseDataPicker(){

 $( "#startDate" ).datepicker({
    defaultDate: "+1w",
    showWeek: true,
    firstDay: 1,
    changeMonth: true,
  //  numberOfMonths: 3,
   onClose: function( selectedDate ) {
     $( "#endDate" ).datepicker( "option", "minDate", selectedDate );
   }
 });
 $( "#endDate" ).datepicker({
     defaultDate: "+1w",
    showWeek: true,
    firstDay: 1,
    changeMonth: true,
  //  numberOfMonths: 3,
   onClose: function( selectedDate ) {
     $( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
   }
 });
 }

Hope That helps! RA

0

btw i will try to explain the way i solved it, cause i think is easier this way.

im not an expert in this matters, so forgive me if I do not use the correct terms to explain it.

if u have 2 places in the same page u want to load datepicker, u got to duplicate the function:

$(function() {
    $( "#datepicker" ).datepicker({
      showOn: "button",
      buttonImage: "images/calendar.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      addClass:".ccCFcalV2"
    });    
});       

$(function() {
    $( "#datepicker2" ).datepicker({
      showOn: "button",
      buttonImage: "images/calendar.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      addClass:".ccCFcalV2"
    });
});

and add the class "datepicker2" to the second place u want to call the datepicker. it works, almost for me

Hope it helps someone, if u consider this a dumb solution, let me know and i'll remove it

have a nice day!

0

If you need to show more than one time in the same view the calender and it only show's one time try this:

document.getElementById("div_Validade").onclick = function () { SetZIndex() };

function SetZIndex() {
    document.getElementById("ui-datepicker-div").style.zIndex = "999999";
}

div_Validade corresponds to the div id where the input is placed,

ui-datepicker-div is infragistics element that is not shown.

0

initialize the datepicker on ajax success method.

Not the answer you're looking for? Browse other questions tagged or ask your own question.