JQuery date picker not working on input field generated by ajax

I have an input field that is created via Ajax from the server side and inserted into the current page. My problem is the jQuery date picker doesn't work on the input field when it is created via Ajax, but it does work when the field is directly placed on the page.

Below is a shortened version of my code.

HTML code:

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

      

And here is the jQuery code that should activate the datepicker on it.

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

      

And here 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>

      

As I said, this works well if the input field is simply encoded on the page. But when inserted into the DOM as the return string of an Ajax call, the date picker no longer works.

Does anyone know how to fix this?

NOTE . I have updated the question to include codes showing what exactly is going on as per @AkshayKhandelwal's comment

+3


source to share


4 answers


try it



success: function() {
  $('#datefield').datepicker();
}

      

+2


source


Datepicker no longer works because you are replacing the existing one with a new one. So the binding is no longer valid since the referenced datepicker does not exist.



You have to reinstall the datepicker after inserting the new datepicker in the dom.

+1


source


You need to reinitialize the date collector in Ajax because you are replacing the existing one with a new one.

$.ajax({
        type: "POST",
        url: "path" ,
        success: function(data) {
            $('#content').html(data);
            $("#datefield").datepicker();
        } ,
        error: function () {
            alert('Error');
        }
    });

      

Hope it helps!

+1


source


When you use $.ajax

, you should probably follow these steps:

var _ajax = function(url, data, type){
    return $.ajax(url, {
        data: data
        type: type
    })
}

      

And use it like below:

_ajax('handler.ashx', null, 'POST').done(function(response){
    // this block of code will execute when `ajax request` is finished !
    // for you case:
    $('#datefield').datepicker();
 });

      

+1


source







All Articles