2012-12-14 157 views
5

我有一個jQuery日期選取器字段,當用戶點擊一個Add按鈕時,我正在克隆它。 我希望日期選取器出現在屏幕上隨後添加的字段中。現在日期選擇器僅出現在第一個字段中,並且not for the added/cloned fieldsjquery datepicker不適用於克隆元素

在檢查了很多關於類似主題的帖子之後,我在這個階段能夠達到。 以下是我的代碼到目前爲止。

<div class="repeatingSection"> 
<a href="#" class="deleteDate" style="display: none;">-Delete</a> 
<input type="text" class="dateListValues" style="position: relative; z-index:100000;" 
     id="dateListValues_1" size="15" /> 
</div> 
<a href="#" class="addDate">+ Add</a> 

JS:

// Add a new repeating section 
$('.addDate').click(function(){ 
    var currentCount = $('.repeatingSection').length; 
    var newCount = currentCount+1; 
    var newID; 
    var lastRepeatingGroup = $('.repeatingSection').last(); 
    var newSection = lastRepeatingGroup.clone(); 
    newSection.insertAfter(lastRepeatingGroup); 
    newSection.find("input").each(function (index, input) { 
     input.id = input.id.replace("_" + currentCount, "_" + newCount); 
     input.name = input.name.replace("_" + currentCount, "_" + newCount); 
     input.value = ""; 
      //removing the additional hasDatepicker class 
     $('#'+input.id).removeClass('hasDatepicker'); 
    }); 

    return false; 
}); 

    $('.dateListValues').each(function(){ 
    $(this).datepicker(); 
    }); 

感謝。

+0

你爲什麼要刪除hasDatepicker類? –

+0

早得早,我沒有刪除它。但在這裏閱讀http://stackoverflow.com/questions/5788999/jquery-datepicker-on-cloned-elements ..所以嘗試這樣做也 – DarkKnightFan

回答

4

您需要初始化新創建的元素上的datepicker插件。試試你的return false;前右加入這一行:點擊功能裏面

newSection.find(".dateListValues").datepicker(); 
+0

優秀!它的工作...感謝很多隊友.. – DarkKnightFan

+0

必須等待2多分鐘:P – DarkKnightFan

+0

@DarkKnightFan謝謝:D –

1

initailize日期選取器..

$('.addDate').click(function(){ 
var currentCount = $('.repeatingSection').length; 
var newCount = currentCount+1; 
var newID; 
var lastRepeatingGroup = $('.repeatingSection').last(); 
var newSection = lastRepeatingGroup.clone(); 
newSection.insertAfter(lastRepeatingGroup); 
newSection.find("input").each(function (index, input) { 
    input.id = input.id.replace("_" + currentCount, "_" + newCount); 
    input.name = input.name.replace("_" + currentCount, "_" + newCount); 
    input.value = ""; 
     //removing the additional hasDatepicker class 
    $('#'+input.id).removeClass('hasDatepicker'); 

}); 
    newSection.find(".dateListValues").datepicker(); //here 
    return false; 
}); 
+0

你不應該把你的代碼在每個循環 –

+0

是的..正確...謝謝..: )..編輯..反正我認爲OP得到了答案.. :) – bipen

+0

謝謝@bipen反正! :) – DarkKnightFan