2

I am dynamically adding new elements and these elements looks like this:

<div id="cars">
  <input type="text" name="car_added[]" class="car" />
  <input type="text" name="car_added[]" class="car" />
  <input type="text" name="car_added[]" class="car" />
  <input type="text" name="car_added[]" class="car" />
  <input type="text" name="car_added[]" class="car" />
</div>

If these elements would be static, I could add a handler on them easily with this code:

$(".car").each(function(){$(this).datetimepicker();})

and after clicking in the input, the date-time widget will display.

But how to do this for dynamically added elements? I've tried the following approach, but it doesn't work:

$('#cars').on('click', '.car', function() {
    $(this).datetimepicker();
});

How to implement into this snippet the .each part?

Thank you in advance.

user984621
  • 46,344
  • 73
  • 224
  • 412

1 Answers1

2

Try this : You need not to iterate and then apply datepicker to element. Just call datetimepicker() as shown below

$('#cars .car').datetimepicker();

EDIT - to add datetimpicker on dynamically generated elements, attache it when you are adding dynamically generated elements.

For Example - I am adding elements on button click. I need to add datetimepicker at the same time. See below code and jsfiddle demo

$(function(){
    //add datetimepicker for existing elements
    $('#cars .car').datepicker();
    
    //add datetimepicker for dynamically added elements when adding it
    $('#clickMe').click(function(){
      var newElement = $('<input type="text" name="car_added[]" class="car" />');
      //add datepicker here
      newElement.datepicker();  
      $('#cars').append(newElement);
    });
});

JSFiddle Demo

NOTE- OP has used datetimepicker but please make note I have used datepicker instead of datetimepicker.

Community
  • 1
  • 1
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57