MegaNairda
MegaNairda

Reputation: 839

jQuery dynamically created datepicker not working

I already did what most of the solutions I see but it doesn't work on mine.

Here's my code:

function regenerateDatePickers()
{
  var length = $( ".forduplication" ).length;
  alert( length );
  for ( var i = 1 ; i <= length ; i++ ) {
    $( "#endDate" + i ).removeClass( "hasDatepicker" );
    $( "#endDate" + i ).datepicker();
  }
}

Only the original datepicker field is working. The cloned ones are not. The Weird thing though is that my dynamically created "chosen"* fields are working.

*chosen http://harvesthq.github.com/chosen/

EDIT - Added HTML code

<tr class="forduplication">
  <td>
    ...
    ...<!--lots of other HTML codes-->
    ...
  </td>
  <td><input id="endDate1" name="endDatefield1" size="10"></td>
  ...
</tr>

Upvotes: 0

Views: 3297

Answers (2)

Dhiraj
Dhiraj

Reputation: 33618

Update 06/01/15

.live() is not longer supported. Using .on() this can be solved.

$('body')
        .on('click', '.datePick', function() {
            $(this).datepicker();
        })
        .on('focus', '.datePick', function() {
            $(this).datepicker();
        });

You could use live and focusin

Have a class for all the input fields, in this case I used datePick as the class

$('input.datePick').live('focusin', function() {
    $(this).datepicker();
});​

Hope this helps

Upvotes: 4

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

One way to do it is to destroy and reassign datepicker on every click but it has performence issue

$('input[id^="endDate"]').live('click', function() {
    $(this).datepicker('destroy').datepicker({showOn:'focus'}).focus();
});

it works but remove and add datepicker every time you click on a input. So it's bettter if you can do this just after cloning the input like

....clone().datepicker('destroy').datepicker({showOn:'focus'}); 

and then add that element to where you want it to be.

Upvotes: 0

Related Questions