复制表单部分

Duplicating form sections

希望有人可以帮助我完成下面的代码片段。单击按钮时,我试图在我的网站上复制表单字段。

问题是,我无法在同一个 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;
});

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() 函数和特定的 class form-section 来定位父 div。你也必须更换:

.appendTo('.duplicate-sections');

作者:

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

因为如果你只给选择器留下 class duplicate-sections 新形式将附加到所有带有这个 class 的元素,你必须指定与单击的 href Add Section.

最后要做的是在每个添加部分 link 添加一个额外的属性 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());                
})

并通过单击 link 获取相关表格,使用 :

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

希望这对您有所帮助。