复制表单部分

时间:2016-11-08 22:56:23

标签: jquery forms clone form-fields

希望有人可以帮助我使用下面的代码段。我点击按钮时尝试复制我网站上的表单字段。

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

1 个答案:

答案 0 :(得分: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给你的小学生,新的表格会附加到这个班级的所有元素,你必须指定与点击的href Add Section相关的一个。 / p>

最后要做的是在每个添加部分链接中添加一个额外的属性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')];

希望这有帮助。