Datepicker only changes date in first row of table
When you're initiating the DatePicker
widget by adding it to the elements with class
datepicker
, it will work just on the elements that are part of the page on that moment.
For every other element added after this first call:
$('.datepicker').datepicker();
Which happens in your click
event handler, you need to add the DatePicker
to them, even though they also have the class
datepicker
.
They're new elements in the page so:
$(function () {
// Adding DatePicker to the elements already in the page.
$('.datepicker').datepicker();
$('#add-row').on('click', function (e) {
e.preventDefault();
var tableBody = $('#periodsTable > tbody');
var lastRowClone = $('tr:last-child', tableBody).clone();
//setting periodId to -1 for any created periods
$('td:first input[name=periodIds]', lastRowClone).val("-1");
tableBody.append(lastRowClone);
// Adding DatePicker to the new element added to the page.
// As the cloned element has the class hasDatepicker already there,
// DatePicker thinks it's initialised for it.
// You need to remove this class before adding DatePicker to it.
lastRowClone.find('.datepicker').attr('id','').removeClass('hasDatepicker').datepicker();
});
});
Note: Like I mentioned in the comments, be aware of elements IDs to not get duplicated. Every ID in the page should be unique. Otherwise your markup will be invalid and any jQuery
selector pointing to that ID will return just the first occurrence and will ignore the rest.
Note 2: Your inputs
have type
set to date
. In modern browsers this will cause a conflict between the HTML 5
native calendar and the jQuery
DatePicker
one.
Note 3: Your second input
doesn't have the class
datepicker
set.
Note 4: Although you may not see any duplicated ID
in your HTML
markup, DatePicker
gives the element a random ID
when added to it, if the element doesn't have one. When you clone this element, you're creating a new element sharing this same ID
, which will cause the DatePicker
to always set the Date
just in the first input
. Find a way to give your elements proper and unique IDs
to avoid this and many other issues.
Demo
After cloning give unique ids to your input fields. Then add datepicker to that input. And hope that this will solve your problem.
$("id").datepicker(); on click event or after cloning.