Home > Programming > Cloning table rows and jQuery UI Datepicker()

Cloning table rows and jQuery UI Datepicker()

December 17th, 2009 ^Lestat Leave a comment Go to comments

I’m rather new to both javascript and jQuery. I ran into an issue while cloning table rows that had inputs, and jQuery UI datepicker.

The cloned datepicker input would insert the picked date into the original inputs rather than the cloned row.
cloneDatepicker

The inputs in my table rows had no ID’s. So what I found was either jQuery or UI was dynamically creating it’s own DOM id’s for the inputs in the table rows that had the datepicker call. Datepicker also was dynamically inserting a class “hasDatepicker” into the inputs that had the datepicker call.

I resolved this by:
1. Looping through the cloned rows inputs looking for any inputs with the class “hasDatepicker”.
2. Removing the hasDatepicker class from any inputs with that class.
3. Getting that inputs current id, incrementing it by 1, and reassigning it.
4. Re-initializing the datepicker call.

<script type="text/javascript">

$(document).ready(function(){

  // -- Clone table rows
  $(".cloneTableRows").live('click', function(){
    // do the cloning...

    // new rows datepicker need to be re-initialized
    $(newRow).find("input").each(function(){

      // if the current input has the hasDatpicker class
      if($(this).hasClass("hasDatepicker")){
        var this_id = $(this).attr("id"); // current inputs id
        var new_id = this_id +1; // a new id
        $(this).attr("id", new_id); // change to new id
        $(this).removeClass('hasDatepicker'); // remove hasDatepicker class
        $(this).datepicker(); // re-init datepicker
      }

    });

  });

});

</script>

Whats really neat about this particular js, is that you can call it from any table that has an id.

The only thing I have yet to figure out is how to reset the cloned datepicker to use the default class called date format.

Categories: Programming Tags:
  1. March 22nd, 2010 at 17:18 | #1

    Hi ,

    I’ve just hit the same problem in jQuery, (trying to clone/duplicate table rows) so glad I found your blog post! After a bit more refactoring, I streamlined it a bit more. Take a look, see what you think:

    $(‘.hasDatepicker’, newRow).each(function(){ $(this).removeClass(‘hasDatepicker’).removeAttr(‘id’).datepicker( { dateFormat: ‘dd/mm/yy’ } ); });

    Now instead of incrementing the ID, we remove it and let the datepicker re-init take care of that!

    Cheers, Lee.

  2. March 22nd, 2010 at 17:59 | #2

    @Lee Kelleher
    Cool and thanks for the non-spam comment hehe. After posting it I realized I could have made it cleaner. I havent tried your way of doing it. What I am curious about is re-init-ing the datepicker again. Especially on a colorbox form with multiple pickers. Would re-init-ing (hard to spell) cause problems?

  3. scott
    June 15th, 2010 at 02:24 | #3

    cheers guys.

  1. No trackbacks yet.