问题
I am trying to create a form in which elements are added dynamically by cloning existing elements in the form. Now the problem i am facing is when i cloned textbox which has class "datepicker".When I select the date from cloned element it's selected value shows in the first element from which I cloned it.
Here is the code:
$(copiedDiv).find('input[type="text"]').filter('.datepicker').removeClass('hasDatepicker').datepicker();
and in document.ready I tried this:
$(function () {
$(".datepicker").datepicker();
});
and this:
$(function () {
$(".datepicker").each(function(){$(this).datepicker()});
});
but both gives the same result. Plz guide me. . Thanx
回答1:
As you are creating input elements dynamically by cloning original div, here .clone()
will do shallow cloning and not deep cloning and hence input box instance will be same always and hence datepicker will refer to original input box.
You can remove id
and class
of the copied input box and then apply datepicker
on it.
Please see below jquery code :
$(function(){
$('input[type=button]').click(function(){
var copiedDiv = $('#container').clone();
var input = $(copiedDiv).find('input[type="text"]');
$(copiedDiv).removeAttr('id');
$(input).removeAttr('id').removeClass('datepicker hasDatepicker').val('');
$(input).datepicker();
$('#container').after(copiedDiv);
});
// bind datepicker to existing input with class="datepicker"
$(".datepicker").datepicker();
});
Demo
来源:https://stackoverflow.com/questions/25258256/datepicker-selected-value-always-goes-on-the-first-textbox