0

I am using bootstrap datepicker in my page.

The form in which I am using this has multiple datepickers generated dynamically.

Now case is when you click first input element and select date then it works for that input field,

Now add another element and click in that input field. The datepicker does not initialize properly.

It works fine if you first add elements and click in the inputs..

Here is what I've tried so far..

$(function() {
  var addMilIterator = 0;
  $(document).on('click', '[data-ele="addMil"]', function(e) {
    var clone = $('.milestones-form').first().clone(true);

    $(clone).find('[name]').each(function() {
      var name = $(this).attr('name');
      $(this).val("");
      $(this).attr('name', name + '_' + addMilIterator);
    });
    addMilIterator++;
    $('.milestones-form').last().after(clone);
  });
  $(document).on('focus', '[name^="date"]', function() {
    $(this).datepicker({

    })
  });
});

I've created a fiddle for that if it helps. Any hint will do. Link to fiddle

Please don't give negative remarks just because my editing is poor. Thanks everybody...

Ashish Joshi
  • 311
  • 4
  • 16
  • I think this might help you out, you might need to change your code a little but this should be exactly what you are looking for - http://stackoverflow.com/questions/32694306/use-jquery-datepicker-on-dynamically-created-fields – TrojanMorse Jan 20 '17 at 09:16

2 Answers2

0

You have to make sure you Clone your input properly. clone(false)

$(function() {
  var addMilIterator = 0;
  $(document).on('click', '[data-ele="addMil"]', function(e) {
    var clone = $('.milestones-form').first().clone(false);

    $(clone).find('[name]').each(function() {
      var name = $(this).attr('name');
      $(this).val("");
      $(this).attr('name', name + '_' + addMilIterator);
    });
    addMilIterator++;
    $('.milestones-form').last().after(clone);
  });
  $(document).on('focus', '[name^="date"]', function() {
  console.log($(this).attr("name"));
    $(this).datepicker({

    })
  });
});

Please check the update Fiddle

K D
  • 5,889
  • 1
  • 23
  • 35
0

This is because every clone you are creating onclick has the same id value ie. sandbox-container

attribute id should be unique for the functionality to work.

Solution

Inside your click event when you are creating a clone, you could also generate & attach a unique id value like so.

var clone = $('.milestones-form').first().clone().prop('id', 'sandbox-container'+ num++ );

before which you need to initialize the num OUTSIDE the click event. So the entire JQuery code would look like.

$(function() {
  var addMilIterator = 0;
  var num = 1;

  $(document).on('click', '[data-ele="addMil"]', function(e) {

    var clone = $('.milestones-form').first().clone().prop('id', 'sandbox-container'+ num++ );

    $(clone).find('[name]').each(function() {
      ...
      ...

Your Fiddle updated

Nikhil Nanjappa
  • 6,454
  • 3
  • 28
  • 44