使用带有增量表单字段名称的Jquery进行表单克隆

时间:2016-05-11 12:31:04

标签: jquery forms clone

我的表单有两个字段是简短描述和长描述最初表单文件名称是部分[新] [1] [描述] 部分[新] [1] [ldescription ]

我想生成克隆表单字段,这些字段生成 section [new] [2] [description] section [new] [2] [ldescription] 等名称。 每当我克隆新表格时,它应该生成表格字段名称,其中增量ID介于 section [new] [incrementid goes here] [description]

如何使用正则表达式或任何其他jquery技术实现这一目标?

以下是我用于表单克隆的代码

jQuery("button.add").on("click", clone); 

function clone(){
var clone = jQuery(this).parents(".pbone_section_default").clone()
    .appendTo("#section_list")
    .attr("id", "pbone_section_default_" +  cloneIndex)
    .find("*")
    .each(function() {
        // here we can put any logic to achieve desire element name  
        this.name = logic goes here;
    })
    .on('click','button.delete',remove);
};

2 个答案:

答案 0 :(得分:3)

是的,可以完成(你很接近)..假设您使用的是基于 0的索引(即从section[new][0][description]开始),请尝试以下代码:

function clone(){
    var $clone = $(".pbone_section_default").last(),
        index = $clone.index();

    $clone.clone()
          .appendTo("#section_list")
          .find("[name*='["+index+"]']")
          .each(function(){
            $(this).attr("name", $(this).attr("name").replace("["+ index +"]", "["+ parseInt(index+1) +"]"));
          });
};

请在此处查看工作示例:FIDDLE

无论如何,我建议您使用模板引擎,例如MustacheUnderscore ..但有很多..检查this article并查看哪些更适合您的项目

答案 1 :(得分:2)

您可以使用.match().replace()查找字符串中的数字并将其增加:

.each(function() {
    this.name = incrementNumberinString(this.name);
});

var incrementNumberinString = function (string){
  var i = parseInt(string.match(/\d{1}/g))+1;
  return string.replace(/\d{1}/g, i)
}

正则表达式将找到任何正好存在1位的数字。

有关正则表达式的示例,请参阅here

注意:这只能在输入名称中只有1个数字的情况下才能工作。

Working Example