开发者

jQuery datepicker won't work on a AJAX added html element

开发者 https://www.devze.com 2023-02-07 12:10 出处:网络
I have a jQuery datepicker function bound to the \"birth开发者_运维知识库day\" input html element, written in the page header:

I have a jQuery datepicker function bound to the "birth开发者_运维知识库day" input html element, written in the page header:

<script type="text/javascript">
    $(function() {
        $( "#birthday" ).datepicker();
    });
</script>

Next, I have some AJAX functionality - it adds new input html element to the page. That element is:

<input type="text" id="birthday" value="" class="detail-textbox1" />

Clicking on that birthday element does not pop up the date picker below the text field. I expected this, as the element is added after the page is loaded, thus it isn't in relation with the function provided in the header.

How can I make it work? I tried moving the script from the header to the body, but nothing seems to work. Thanks.

P.S. If I create an input html element with id="birthday" in the page body, everythig works as expected. It appears that only the elements added through AJAX are dysfunctional.


I'm a bit late to the party, but for thoroughness - and with the .live() function being deprecated from jQuery 1.7 onwards - I thought I'd provide an updated solution based on my experiences, and from all the help I got from other answers on StackOverflow!

I had a situation where I needed to add the datepicker functionality to input fields that were being added to the DOM through AJAX calls at random, and I couldn't modify the script making the AJAX calls to attach the datepicker functionality, so I opted for the new shiny .on() function with its delegation features:

// do this once the DOM's available...
$(function(){

    // this line will add an event handler to the selected inputs, both
    // current and future, whenever they are clicked...
    // this is delegation at work, and you can use any containing element
    // you like - I just used the "body" tag for convenience...
    $("body").on("click", ".my_input_element", function(){

        // as an added bonus, if you are afraid of attaching the "datepicker"
        // multiple times, you can check for the "hasDatepicker" class...
        if (!$(this).hasClass("hasDatepicker"))
        {
            $(this).datepicker();
            $(this).datepicker("show");
        }
    });
});

I hope this helps someone, and thanks for all the answers so far that led me to this solution that worked for me! :)


You need to use .live() so that any newly added elements have the event handler attached: http://api.jquery.com/live/

$('#birthday').bind('load', function() {
    $(this).datepicker();
});

EDIT

.live() documentation states, that it is a bit out of date. With new versions of jquery (1.7+) use .on().


Boris, JK: This was super helpful for me. I have also found that you can use the following for AJAX html if you want to use Datepicker's date range selection:

$('#groundtransporation').live('focus', function() {
var gt = $( "#rentalPickUp, #rentalDropOff" ).datepicker({
  defaultDate: "+1w",
  changeMonth: true,
  numberOfMonths: 2,
  onSelect: function( selectedDate ) {
    var option = this.id == "rentalPickUp" ? "minDate" : "maxDate",
      instance = $( this ).data( "datepicker" ),
      date = $.datepicker.parseDate(
        instance.settings.dateFormat ||
        $.datepicker._defaults.dateFormat,
        selectedDate, instance.settings );
    gt.not( this ).datepicker( "option", option, date );
  }
});
});


I got another case. My script is copying last table elements including datepicker.

The jquery will not working because the copied element has mark that it "hasDatepicker".

To activate datepicker in new element, remove that class name and the initiate it, like this.

$("#yournewelementid").attr("class","your-class-name"); $("#yournewelementid").datepicker();


your issue is always happens when elements don't exist when you try to initialize it.

When you use $(function(){/** some code **/}); elements must exsit on the document, it means that has to be on the html so you could can create a function to initialize the component or initialize it on the success event after been add it to the document.

Is important to first add the external html load in the ajax request to the document before you try to initialize it or it won't be initialize at all.
Example:

$.ajax({
     url:"ajax_html.html",
     dataType:"html"
}).done(function(html){
     $("#selector").html(html)
     init();
});

function init(){
     $(".birthday").datepicker({});
}


You could initialize the date picker for the newly added element within your ajax success callback:

 $.ajax({

    ...

    success: function(response) {
        if(response.success) {
              $(body).append(response.html);
              $("#birthday").datepicker();
        }
    }
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消