javascript – jQuery datepicker not working on dynamic HTML-ThrowExceptions

Exception or error:

I have asked this question before and also here. However, none of the proposed answers worked. And days after, the problem is still not resolved. Hence my asking again, with a few more details to see if someone could help me get it resolved.

I have an input field that is generated via Ajax from the server-side, and inserted into the current page. My problem is: the jQuery date picker is not working on the input field when it is generated via Ajax, but it works when the field is directly placed in the page.

Below, I include a scaled-down version of my code.

HTML code:

<form id="user-form"></form>

And here’s the jQuery code that’s supposed to activate the datepicker on it.

$.ajax({
   type: "GET",
   url: "/inputfield-loader.php" ,
   success: function(data) {
      $('#user-form').html(data);
      $("#datefield").datepicker();
   } 
});

And here’s inputfield-loader.php

<input type="text" name="firstname" id="firstname"></div>
<div><input type="text" name="email" id="email"></div>
<div><input type="text" name="birthdate" id="datefield"></div>
<div><input type="submit"></div>

Everything works fine if the input field is just hard-coded into the page. But when inserted into the DOM as the return string of an Ajax call, the date picker no longer works. However, when I use Chrome to inspect the datefield field, I see that it has added the jQuery datepicker class hasDatepicker to it, indicating that the call to the jQuery.datepicker() method worked. But on click of the field, I don’t see the date picker pop up.

As per @dfsq’s suggestion, here is the fiddle. It comes closer to the original code: http://jsfiddle.net/35kgsjxk/

How to solve:

You’re missing opening div tag in your inputfield-loader.php file, which can cause issue of hiding some elements.

If you’re using correct headers and data type in $.ajax it should work as it’s working on: http://jsfiddle.net/96d8k2m3/

Answer´╝Ü

I was also facing the same issue. I fixed this as,

$(document).bind('click','#datefield',function(){
    $('#datefield').datepicker();
})

Leave a Reply

Your email address will not be published. Required fields are marked *