1

I have a form in which a user can add a set of fields dynamically as needed. The code for that just copies the last entry and increments the counters in the field names (work around for my question here) The code follows:

$("#addBeneficiary").click(function(e) {
    e.preventDefault();
    var beneficiary = $(".beneficiary:last").clone();
    var count = parseInt(beneficiary.find("input:first").attr("id").match(/\d+/), 10);
    beneficiary.find("input").each(function(indx, element) { 
        var name = $(element).attr('name').replace(count, count+1),
            id   = $(element).attr('id').replace(count, count+1);
        $(element).attr('name', name);
        $(element).attr('id', id);
        $(element).val(''); 
    });

    $("#beneficiaries").append(beneficiary);
    datepicker();
});

The last line datepicker(); is just a function that finds all input.datepicker and executes the jQuery UI datepicker() function to add date pickers to those fields. The problem I'm running into is this; the datepicker works fine on the first fields, but when they are dynamically added the datepicker doesn't pop up for the new fields.

I've traced the code execution with logging statements to ensure my datepicker() function is called after the append and that all works. Here is my datepicker() code

var datepicker = function() {
    $("input.datepicker").datepicker();
};

Does anyone know why this is not working as expected?

2
  • Any errors in the console? Why not just .datepicker() the newly created input? Commented Feb 25, 2011 at 22:29
  • No errors and tried that as well, no such luck, focus doesn't produce a datepicker Commented Feb 25, 2011 at 23:01

1 Answer 1

3

My guess is that it has to do with the clone. I know you can accomplish this with a live datepicker activation for they dynamically added elements. Try out this jsfiddle.

$("input.datepicker").live('focus', function(){
    var $this = $(this);
    if(!$this.data('datepicker')) $this.datepicker();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, this works only if the user hasn't focused on the first element that is to be copied before adding more, even changing it to just call datepicker on focus doesn't work
@Jimmy - I can't reproduce what you are talking about. You will no longer need to call datepicker each time a row is added. It only needs to be called onready because it is a live event. Did you try out the example?
I did, was just trying new methods to see if i could get anything working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.