katie hudson
katie hudson

Reputation: 2893

JQuery - cloning a datepicker

I have the following FIDDLE

I am trying to clone a datepicker, so I have

if($(this).hasClass('dateControl')) {
    $(this).removeClass('hasDatepicker').removeData('datepicker')
        .unbind().datepicker({
            dateFormat: "dd-mm-yy"
        });
}

This seems to clone it, but it has some weird behaviour. If I add several rows without inputting any data, they act as normal. However, before adding a row, if I select an option from the datepicker and then add a row, the cloned row has the previous date, and even if I try changing this, it wont change.

Why is this happening?

Thanks

Upvotes: 2

Views: 81

Answers (1)

Tony Hinkle
Tony Hinkle

Reputation: 4742

This is probably not the best solution, but it is the one I found most quickly. I added the $(".dateControl").datepicker("destroy"); line when the add button is clicked because it appears that the bindings get foo-barred during cloning. Then at the end of the handler, initialize the datepickers again, using the dateControl class so that it gets all of them.

I also modified the if statement so that it just clears the value in the new input.

  $("#add_row").click(function() {

    // Added this line to destroy the datepickers so bindings don't
    // get confused during clone.
    $(".dateControl").datepicker("destroy");

    $(".responsibility").select2("destroy");
    $("table tr").eq(1).clone().find("input, select").each(function() {
      $(this).attr({
        'id': function(_, id) {
          return id + i
        },
        'name': function(_, name) {
          return name + i
        },
        'value': ''
      });

      // Changed the code block in the if statement to just clear the
      // input value--it doesn't need to try to fix the datepicker binding
      // here.
      if ($(this).hasClass('dateControl')) {
        $(this).val("");
      }

    }).end().appendTo("table");
    i++;
    $(".responsibility").select2({
      tags: true
    });

    // Add the following to reinitialize the datepicker inputs since
    // they were destroyed earlier.
    $(".dateControl").datepicker({
      dateFormat: "dd-mm-yy"
    });
  });

Upvotes: 1

Related Questions