以下のコードスニペットで誰かが私を助けてくれることを願っています。ボタンがクリックされたときに、サイトのフォーム フィールドを複製しようとしています。
問題は、同じ html ページ上の複数のフォームに対してこれを機能させるのに問題があることです。これは最初のフォームでのみ機能します。2 番目のフォームを追加しようとすると、2 番目のフォームのボタンが 2 番目のフォーム内の最初のフォームを複製します。どんな洞察も大歓迎です!
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>
Jクエリ
//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;
});