2016-11-08 65 views
3

希望有人能夠幫助我下面的代碼片段。我試圖在單擊按鈕時在我的網站上覆製表單域。複製表單部分

問題是,我無法在同一個html頁面上爲多個表單做這項工作。這隻適用於第一種形式。當我嘗試添加第二個表單時,第二個表單上的按鈕與第二個表單中的第一個表單重複。任何有識之士都非常感謝!

HTML

<div class="duplicate-sections"> 
<div class="form-section"> 
    <fieldset> 
     <p> 
     <label for="firstName">First Name:</label> 
     <input name="firstName[]" id="firstName" value="" type="text" /> 
     </p> 
     <p> 
     <label for="lastName">Last Name:</label> 
     <input name="lastName[]" id="lastName" value="" type="text" /> 
     </p> 
     <a href="#" class="remove">Remove Section</a> 
    </fieldset> 
    </div> 
</div> 

<a href="#" class="addsection">Add Section</a> 

jQuery的

//define template 
var template = $('.duplicate-sections .form-section:first').clone(); 

//define counter 
var sectionsCount = 1; 

//add new section 
$('body').on('click', '.addsection', function() { 

    //increment 
    sectionsCount++; 

    //loop through each input 
    var section = template.clone().find(':input').each(function(){ 

     //set id to store the updated section number 
     var newId = this.id + sectionsCount; 

     //update for label 
     $(this).prev().attr('for', newId); 

     //update id 
     this.id = newId; 

    }).end() 

    //inject new section 
    .appendTo('.duplicate-sections'); 
    return false; 
}); 

//remove section 
$('.duplicate-sections').on('click', '.remove', function() { 
    //fade out section 
    $(this).parent().fadeOut(300, function(){ 
     //remove parent element (main section) 
     $(this).parent().parent().empty(); 
     return false; 
    }); 
    return false; 
}); 

回答

0

Working codepen

您對改變這一部分在remove行動:

$(this).parent().fadeOut(300, function(){ 
    //remove parent element (main section) 
    $(this).parent().parent().empty(); 
    return false; 
}); 

爲:

$(this).closest('.form-section').fadeOut(300, function(){ 
    $(this).closest('.form-section').empty(); 
}); 

使用closest()功能和特定的類form-section目標父DIV。你也已經更換:

.appendTo('.duplicate-sections'); 

通過:

.appendTo($(this).prev('.duplicate-sections')); 

因爲如果你離開你只是一個類duplicate-sections新的形式將被追加到所有的元素與這一類slector,你有指定與點擊相關的那一個。

末的事情在每次增加一個額外的屬性data-section添加部分鏈接到指定(基於0)形式的數字:

<a href="#" class="addsection" data-section='0'>Add Section</a> 

然後,所有的形式存儲在數組中:

var forms = []; 

$('.duplicate-sections .form-section').each(function(){ 
    forms.push($(this).clone());     
}) 

並採用獲得與被點擊鏈接相關表格:

var template = forms[$(this).data('section')]; 

希望這有助於。

+0

嗨,感謝您的回覆。我已經爲您提供的修復程序創建了一個codepen,但似乎仍然存在與表單重複有關的問題。不正確。請看這個鏈接:http://codepen.io/EBM84/pen/oYjGzY – EBM84

+0

解決檢查我的更新。 –

+0

我假設這可能意味着可能會將類.duplicate-sections改爲每個表單的特定ID?如果我走這條路線,那麼我是否必須爲每個表單重複相同的Jquery代碼? – EBM84