希望有人可以通过下面的代码片段帮助我。单击按钮时,我试图在我的网站上复制表单字段。
问题是,我无法在同一个 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;
});