JQuery - 克隆一个datepicker

时间:2016-02-09 14:21:56

标签: javascript jquery datepicker

我有以下FIDDLE

我正在尝试克隆一个日期选择器,所以我有

amount

这似乎克隆了它,但它有一些奇怪的行为。如果我在不输入任何数据的情况下添加多行,它们就会正常运行。但是,在添加行之前,如果我从datepicker中选择一个选项然后添加一行,则克隆的行具有上一个日期,即使我尝试更改它,也不会更改。

为什么会这样?

由于

1 个答案:

答案 0 :(得分:1)

这可能不是最佳解决方案,但它是我发现最快的那个。单击添加按钮时,我添加了$(".dateControl").datepicker("destroy");行,因为在克隆过程中绑定看起来是foo-barred。然后在处理程序的最后,使用dateControl类再次初始化datepickers,以便它获取所有这些。

我还修改了if语句,以便它只清除新输入中的值。

  $("#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"
    });
  });
相关问题