Dynamic jQuery UI datepicker elements

岁酱吖の 提交于 2019-12-12 00:07:14

问题


I am using the jQuery UI datepicker function to create a number of date fields in my html form.

I am using the following code to get any input field with a 'datepicker' class to work:

$('.datepicker').each(function() {
    var id = $(this).attr('id').split('_')[0];

    if ($('#'+id+'_value').val()) { 
        var initialdate = new Date($('#'+id+'_value').val());
    }
    else {
        var initialdate = new Date();
    }

    $(this).val($.datepicker.formatDate('DD, d MM, yy', initialdate));
    $('#'+$(this).attr('id').split('_')[0]+'_value').val($.datepicker.formatDate('yy-mm-dd', initialdate));
    $(this).datepicker({
                        'dateFormat': 'DD, d MM, yy',
                        'altField': '#'+id+'_value',
                        'altFormat': 'yy-mm-dd' 
    });
});

However, I'm also using some other javascript to clone a span which contains several form elements. When the new elements are created, the datepicker function does not work.

What can I do to make the new ones work like the existing ones?

Any advice appreciated.

Thanks.


回答1:


As you are probably calling that iteration on document creation, items added to the DOM later are not instantiated as new datepickers, so you would have to explicitly call .datepicker() on each of the newly added elements you wish to enable datepicker on.

Basically, move the code from the iterator above to its own function, then do:

$('.datepicker').each(myDatePickerFunction($(this));

And call the same function on the elements you add later.



来源:https://stackoverflow.com/questions/12247902/dynamic-jquery-ui-datepicker-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!