2017-04-03 41 views
2

我的表单中包含添加更多字段按钮,它动态地添加新的datepicker的每当我单击添加更多字段按钮。当我动态添加新的日期选择器时,以前的日期选择器值重置?

问题是,当前日期字段在datepicker显示当前日期。 但是当我添加新日期选择器通过点击添加更多的字段按钮,它增加了一个更加日期选择器但这次它重置的于前值的DatePicker我已经手动设置。

下面是我的代码: HTML

<div id="container"> 
<input class="datepick" type="text"></input><button class="add">Add</button> 
<input 
</div> 

的JavaScript

$(".datepick").datepicker(); 
$(".datepick").datepicker().datepicker("setDate", new Date()); 
$(document).on('click', '.add', function() { 
    var appendTxt = '<input class="datepick" type="text" /><button class="add">Add</button>'; 
    $("#container").append(appendTxt); 
    $(".datepick").datepicker(); 
    $(".datepick`enter code here`").datepicker().datepicker("setDate", new Date()); 

}); 
+0

你调试的代码流?这两个datepicker不能共享相同的ID? – Komal

回答

3

因为该行的:

$(".datepick").datepicker(); 

所有输入它们具有类.datepick将重新初始化。你应该做这样的事情:

$(".datepick").last().datepicker(); 

$(".datepick:last").datepicker(); 

你添加新的input.datepick后。这是简单的解决方案。

如果您在此容器之后的其他容器中有任何其他.datepick,则此操作不起作用。你应该对附加的datepicker元素非常具体。

你应该这样做:

var appendTxt = '<input class="datepick" type="text" /><button class="add">Add</button>'; 
var newInput = $(appendTxt).appendTo("#container"); 
newInput.datepicker(); 
newInput.datepicker().datepicker("setDate", new Date()); 
相关问题