简体   繁体   中英

jQuery datepicker not working on dynamically inserted html element

This same question has been asked repeatedly, and the only time it has been answered is the one where the fellow was trying to initialise datepicker in the .onReady() function. I am not doing that. In fact, I am actually doing what that solution is doing; implementing datepicker immediately after creating the element.

Here is my template code:

<input type=text name="txt_you_History_From_Date_XXX" id="txt_you_History_From_Date_XXX" class="month-picker inputField" size=16 maxlength=16>

You will notice the month-picker class. Also, you will notice the "XXX" placeholders.

Here is the code that inserts that template code:

//
// find the next available id
//

for (var i = 0; ; i++) {
    if (!$("#divEmployer_" + i.toString()).length) {
        break;
    }
}


//
// get html, and replace the placeholders with id, then append.
//

$.get("content/contentHistoryEmployerTemplate.html", function (data) {

    while (data.indexOf("XXX") >= 0) {
        data = data.replace("XXX", i.toString());
    }

    $("#employerDIV").append(data);
});


//
// activate datepicker on all month-picker class elements
//

$('.month-picker').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'MM yy',
    onClose: function (dateText, inst) {
        $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
    }
});

//alert("here");

I do see the "here" alert if I uncomment it, so I know the code is being run.

The datepicker() throws no error.

I know the function is available because if I comment out my jquery-ui-min.js in my <HEAD> , a reference to datepicker() does then throw an error.

But the field does not respond when it receives focus. The datepicker does not appear.

Can anyone tell me what's wrong? Thanks!

You are trying to instantiate the datepicker before the element exists. Put that code inside the async callback.

$.get("content/contentHistoryEmployerTemplate.html", function (data) {

    while (data.indexOf("XXX") >= 0) {
        data = data.replace("XXX", i.toString());
    }

    $("#employerDIV").append(data);

    // PUT DATEPICKER HERE
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM