Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用jQuery复制表单块_Jquery_Forms_Duplicates_Increment - Fatal编程技术网

如何使用jQuery复制表单块

如何使用jQuery复制表单块,jquery,forms,duplicates,increment,Jquery,Forms,Duplicates,Increment,我对jQuery很陌生,所以请容忍我 我需要复制表单的一块,用户可以在其中创建多个/不确定的作业角色。我在这里找到了我想要的东西的近似值:,但它还没有完全完成工作 出了什么问题: 它并没有为新块的每个表单字段添加一个新的编号来完成它们 我仍然需要: 将新标题添加到每个块的顶部,每次增量为1(作业2、作业3等) 表单字段的ID和“for”每次递增一个(primaryJobRole2、primaryJobRole等) 我设法让越来越多的数字进入元素,但问题是第一次它将是primaryJobRole2

我对jQuery很陌生,所以请容忍我

我需要复制表单的一块,用户可以在其中创建多个/不确定的作业角色。我在这里找到了我想要的东西的近似值:,但它还没有完全完成工作

出了什么问题: 它并没有为新块的每个表单字段添加一个新的编号来完成它们

我仍然需要: 将新标题添加到每个块的顶部,每次增量为1(作业2、作业3等) 表单字段的ID和“for”每次递增一个(primaryJobRole2、primaryJobRole等)

我设法让越来越多的数字进入元素,但问题是第一次它将是primaryJobRole2,然后下一次它将是primaryJobRole23等等

我确信答案就在眼前,但我已经发展出了隧道视野!提前谢谢

我的HTML是:

<div class="repeat-role">
  <h3>Current Role</h3>

  <label for="primaryJobRole">Job Role:</label>  
  <input id="primaryJobRole" name="primaryJobRole" type="text">

  <label for="currentOrganisation">Current Organisation Name:</label>  
  <input id="currentOrganisation" name="currentOrganisation" type="text"> 

  <label for="currentTitle">Current Title:</label>  
  <input id="currentTitle" name="currentTitle" type="text">

</div>

JSFiddle here:

我没有试图修改最后一节,而是编辑了您的逻辑,将原始节用作每个新节的模板。这样,您只需要附加新计数,而不需要尝试替换它们

$('.add-role').click(function () {
    var currentCount = $('.repeat-role').length;
    var newCount = currentCount + 1;
    var lastRepeatingGroup = $('.repeat-role').last();
    var template = $('.repeat-role').first();
    var newSection = template.clone();
    var newHeading = $('h3', newSection).append(' ' + newCount);

    lastRepeatingGroup.removeClass('current-role');
    newSection.insertAfter(lastRepeatingGroup).hide().addClass('current-role new-role').slideDown(1000);
    newSection.find("input").each(function (index, input) {
        var i = $(this).attr('id');
        $(this).attr('id', i + newCount);
    });
    newSection.find("label").each(function (index, label) {
        var l = $(this);
        l.attr('for', l.attr('for') + newCount);
    });
    return false;
});

更新:

我已经更新了答案和fiddle以使用.on()而不是.click()。只有第一行受影响:

$(document).on('click', '.add-role', function () {
  ...
});

小提琴:

完美-谢谢!我知道它正在克隆自己的最后一个版本,但不知道如何只复制最初的代码块-再次感谢!当我单击第二个添加角色添加另一个角色时,它将删除所有角色。
$(document).on('click', '.add-role', function () {
  ...
});