Cloning datepicker objects [JQuery]

后端 未结 4 699
温柔的废话
温柔的废话 2021-01-02 12:25

I have an input field that I define as a datepicker through a css class. I now want to clone this input field and have it so the cloned inputs are also datepickers.

相关标签:
4条回答
  • 2021-01-02 12:28

    Change it to this:

    $('.calendar:last').clone(false).removeClass('hasDatepicker').insertAfter('.calendar:last').datepicker();
    
    0 讨论(0)
  • 2021-01-02 12:29

    to bad I can't comment anymore on the answer given above, but the code still fales! The datepicker shows up at the cloned input element , but uses the selected date value in the original input field and leaves the cloned input field blank .. Any suggestions?

    edit:

    Using the following code fixed it for me..

    $('.datum',clone).removeClass("hasDatepicker").attr('id',"").datepicker();
    

    ( note that I have cloned a wrapper , and am only targeting the 'datum' input field in that wrapper )

    After removing the class as suggested above , I also remove id of the cloned input element. It's the same as the original, so that's why I was updating the original input field with the selected date in the datepicker box.

    0 讨论(0)
  • 2021-01-02 12:42

    This might be a little late, but all the suggestions above didn't work for me, I came up with an easy solution for this.

    First, what is causing the problem: JQuery assign datepicker to element id. if you are cloning element, then same id might be cloned as well. which jQuery doesn't like. You might end up with either receiving null reference error or the date being assigned to first input field regardless which input field you click on.

    Solution:

    1) destroy datepicker 2) assign new unique ids to all input field 3) assign datepicker for each input

    Make sure your input is something like this

    <input type="text" name="ndate[]" id="date1" class="n1datepicker">
    

    Before you clone, destroy datepicker

    $('.n1datepicker').datepicker('destroy');
    

    After you clone, add these lines as well

    var i = 0;
    $('.n1datepicker').each(function () {
        $(this).attr("id",'date' + i).datepicker();
        i++;
    });
    

    and the magic happens

    0 讨论(0)
  • 2021-01-02 12:48

    I made the following changes and it works.

    Before:

     $('#clone').click(function()
     {
      $('.calendar:last').clone().append().insertAfter('.calendar:last');
     });
    

    After:

     $('#clone').click(function()
     {
      $('.calendar:last').clone().append().insertAfter('.calendar:last').attr('id',"");
     });
    
    0 讨论(0)
提交回复
热议问题