3
votes

I'm trying to apply a datepicker control to cloned input fields. What I'm doing is finding the table row I want to clone, clone it with clone(false) and then for each input with a class .date call datepicker() on them. The code is as follows:

$('.repeat').bind('click', function() {
    var parentEl = $(this).parents('.root');
    var lastRow = jQuery.makeArray($(parentEl).find('.last'));
    var newRow = $(lastRow).clone(false);
    $(lastRow).removeClass('last');
    $(newRow).addClass('last');
    newRow.find('input').each(function() {
        this.name = this.name.replace(/\[(\d+)\]/, function(str, p1) {
            return '[' + (parseInt(p1, 10) + 1) + ']';
        });
    }).end().insertAfter($(lastRow));

    newRow.find('.date').each(function() {  
        $(this).removeAttr('id');
        $('.date').datepicker({ dateFormat: 'dd-mm-yy', changeYear: true, yearRange: '1970:2010' });
    });
});

Now both $(this).datepicker() and $('.date').datepicker() fail to attach a datepicker control to input.date.

The above code works as expected except for the datepicker bit.

Anybody have any ideas?!

2
Have you tried attaching them to the DOM first, before applying the datepicker ?Gabriele Petrioli
Sorry, my mistake. There is code that I didn't post that inserts newRow after lastRow (insertAfter($lastRow)) after it does some formatting. I presume that that does attach it to the DOM, or am I mistaken?jimmy
indeed that would add it in the DOM. I posted an answer with an additional change you need to make for the code to work..Gabriele Petrioli

2 Answers

14
votes

Seems to work if you add the row first (before applying the datepicker) and also remove the class added by the datepicker .hasDatepicker.

$('.repeat').bind('click', function(){
        var parentEl = $(this).parents('.root');
        var lastRow = jQuery.makeArray($(parentEl).find('.last'));
        var newRow = $(lastRow).clone(false, false);
        $(lastRow).removeClass('last');
        $(newRow).addClass('last');
        $('.root').append(newRow); // added this

        newRow.find('.date').each(function() {
            $(this).removeAttr('id').removeClass('hasDatepicker'); // added the removeClass part.
            $('.date').datepicker({dateFormat: 'dd-mm-yy', changeYear: true, yearRange: '1970:2010'});
        });
});

demo: http://jsfiddle.net/gaby/LCfC2/

0
votes

The class element must be removed and date picker must be then added to the cloned element. Works every time for me no matter whether or not it has been attached to the DOM yet.

$(inputData3).removeAttr("class");
$(inputData3).datepicker();