How to increment values on .clone() in jquery

点点圈 提交于 2019-12-25 08:18:22

问题


I am trying to clone a form and change the form name from (for example) #form and when cloned to #form1 and do the same on the inputs and I am really stuck on how to do this! Any help would be GREATLY appreciated as I have spent ALL DAY trying to figure it out. Here is my code:

HTML:

<div class="avail">
<form action="submit.php" id="form1" method="post">
<input type="text" name="input1" />
<input type="text" name="anotherinput1" />
<input type="text" name="onemoreinput1" />
<input type="submit" name="submit1" value="submit" />
</form>
</div>

 <input type="submit" value="+" id="copy" />

JQUERY (for cloning the div and form):

$("#copy").click(function(e) {
       $(".avail").clone().removeAttr('id').insertBefore(this);
       e.preventDefault();
    });

Please if anyone knows how to do this, I would appreciate it soooo much!


回答1:


You can just count how many avail objects you have and use that as the running count for the new form ID.

$("#copy").click(function(e) {
   var avails = $(".avail");
   var cnt = avails.length + 1;
   avails.eq(0).clone().insertBefore(this).find("form").attr("id", "form" + cnt);
   e.preventDefault();
});

You can see it work here: http://jsfiddle.net/jfriend00/9CU85/

If you also need to update the numbers on the name attributes of the input elements, then you can use this code to do that also:

$("#copy").click(function(e) {
   var avails = $(".avail");
   var cnt = avails.length + 1;
   avails.eq(0).clone().insertBefore(this)
       .find("form").attr("id", "form" + cnt)
       .find("input").each(function() {
           this.name = this.name.replace(/\d+/, cnt);
       });
   e.preventDefault();
});​

You can see this one work here: http://jsfiddle.net/jfriend00/SKjMN/




回答2:


$('#copy').click(function(e){
    var formNode = $('.avail form')[0];
    var idAttibute = $(formNode).attr('id');
    var id = id.charAt(idAttibute.length-1);

    var copy = $(".avail").clone().removeAttr('id');
    $(copy).find('form').attr('id', 'form' + id);
    $(copy).insertBefore(this);

});


来源:https://stackoverflow.com/questions/10037807/how-to-increment-values-on-clone-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!