When I dynamically add a new datepicker are the previous values ​​of the datepicker reset?

I have a form that contains an Add field button that dynamically adds a new datepicker whenever I click the Add More button.

The problem is that the date field in the datepicker displays the current date. But when I add a new Datepicker by clicking the Add extra field button , it adds another Datepicker, but this time it resets the previous Datepicker value that I manually set.

Below is my code: 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());

});

      

+3


source to share


1 answer


Because of this line:

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

      

All inputs that have a class .datepick

will be reinitialized. You should do something like this:

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

      

or



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

      

after adding a new one input.datepick

. It was a simple solution.

If you have another .datepick

in another container after that container, that won't work either. You should be very specific about the added datepicker element.

You must do this:

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());

      

+4


source







All Articles