jQuery的克隆表单字段和增量ID

我有一块表单元素,我想克隆和增加他们的ID使用jQuery的克隆方法。 我已经尝试了一些例子,但是其中很多只是克隆了一个字段。

我的块是这样构成的:

<div id="clonedInput1" class="clonedInput"> <div> <div> <label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label> <select class="" name="txtCategory[]" id="category1"> <option value="">Please select</option> </select> </div> <div> <label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label> <select class="" name="txtSubCategory[]" id="subcategory1"> <option value="">Please select category</option> </select> </div> <div> <label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label> <select name="txtSubSubCategory[]" id="subsubcategory1"> <option value="">Please select sub-category</option> </select> </div> </div> 

很显然,元素排好了很多,但你明白了。

我想保持id结构,即category1,subcategory1等,因为我使用这些dynamic显示select基于父母select的选项,所以如果它有可能有每个克隆块像category1 / category2 / category3等将是很好的。

HTML

 <div id="clonedInput1" class="clonedInput"> <div> <label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label> <select class="" name="txtCategory[]" id="category1"> <option value="">Please select</option> </select> </div> <div> <label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label> <select class="" name="txtSubCategory[]" id="subcategory1"> <option value="">Please select category</option> </select> </div> <div> <label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label> <select name="txtSubSubCategory[]" id="subsubcategory1"> <option value="">Please select sub-category</option> </select> </div> <div class="actions"> <button class="clone">Clone</button> <button class="remove">Remove</button> </div> </div> 

JavaScript – Jquery v1.7及更早的版本

 var regex = /^(.+?)(\d+)$/i; var cloneIndex = $(".clonedInput").length; $("button.clone").live("click", function(){ $(this).parents(".clonedInput").clone() .appendTo("body") .attr("id", "clonedInput" + cloneIndex) .find("*").each(function() { var id = this.id || ""; var match = id.match(regex) || []; if (match.length == 3) { this.id = match[1] + (cloneIndex); } }); cloneIndex++; }); 

只有一个愚蠢的部分:) .attr("id", "clonedInput" + $(".clonedInput").length)但它的工作原理;)

JAvascript – JQuery最近(支持.on())

 var regex = /^(.+?)(\d+)$/i; var cloneIndex = $(".clonedInput").length; function clone(){ $(this).parents(".clonedInput").clone() .appendTo("body") .attr("id", "clonedInput" + cloneIndex) .find("*") .each(function() { var id = this.id || ""; var match = id.match(regex) || []; if (match.length == 3) { this.id = match[1] + (cloneIndex); } }) .on('click', 'button.clone', clone) .on('click', 'button.remove', remove); cloneIndex++; } function remove(){ $(this).parents(".clonedInput").remove(); } $("button.clone").on("click", clone); $("button.remove").on("click", remove); 

工作示例在这里

克隆主元素,从中删除ID号。 在新的元素中,replace每个元素id中的每个id编号的实例,您需要使用新的id编号进行递增。

好的,这里有一个快速的代码。

基本上这部分是最重要的:

 (parseInt(/test(\d+)/.exec($(this).attr('id'))[1], 10)+1 

它parsing当前的id(使用RegEx去除string中的数字)并将其增加1.在你的情况下,而不是'test',你应该把'clonedInput',并且不仅增加主元素id的值,但从内部的三个(类别,子类别和子类别)。 一旦你有新的身份证,这应该很容易。

希望这可以帮助。 🙂

另一个select是使用recursion函数:

 // Accepts an element and a function function childRecursive(element, func){ // Applies that function to the given element. func(element); var children = element.children(); if (children.length > 0) { children.each(function (){ // Applies that function to all children recursively childRecursive($(this), func); }); } } 

然后你可以做一个函数或三个设置你的未克隆表单域的属性和值:

 // Expects format to be xxx-#[-xxxx] (eg item-1 or item-1-name) function getNewAttr(str, newNum){ // Split on - var arr = str.split('-'); // Change the 1 to wherever the incremented value is in your id arr[1] = newNum; // Smash it back together and return return arr.join('-'); } // Written with Twitter Bootstrap form field structure in mind // Checks for id, name, and for attributes. function setCloneAttr(element, value){ // Check to see if the element has an id attribute if (element.attr('id') !== undefined){ // If so, increment it element.attr('id', getNewAttr(element.attr('id'),value)); } else { /*If for some reason you want to handle an else, here you go*/ } // Do the same with name... if(element.attr('name') !== undefined){ element.attr('name', getNewAttr(element.attr('name'),value)); } else {} // And don't forget to show some love to your labels. if (element.attr('for') !== undefined){ element.attr('for', getNewAttr(element.attr('for'),value)); } else {} } // Sets an element's value to '' function clearCloneValues(element){ if (element.attr('value') !== undefined){ element.val(''); } } 

然后添加一些标记:

 <div id="items"> <input type="hidden" id="itemCounter" name="itemCounter" value="0"> <div class="item"> <div class="control-group"> <label class="control-label" for="item-0-name">Item Name</label> <div class="controls"> <input type="text" name="item-0-name" id="item-0-name" class="input-large"> </div> </div><!-- .control-group--> <div class="control-group"> <label for="item-0-description" class="control-label">Item Description</label> <div class="controls"> <input type="text" name="item-0-description" id="item-0-description" class="input-large"> </div> </div><!-- .control-group--> </div><!-- .item --> </div><!-- #items --> <input type="button" value="Add Item" id="addItem"> 

然后,所有你需要的是一些jQuery的善良把它们拉在一起:

 $(document).ready(function(){ $('#addItem').click(function(){ //increment the value of our counter $('#itemCounter').val(Number($('#allergyCounter').val()) + 1); //clone the first .item element var newItem = $('div.item').first().clone(); //recursively set our id, name, and for attributes properly childRecursive(newItem, // Remember, the recursive function expects to be able to pass in // one parameter, the element. function(e){ setCloneAttr(e, $('#itemCounter').val()); }); // Clear the values recursively childRecursive(newItem, function(e){ clearCloneValues(e); } ); // Finally, add the new div.item to the end newItem.appendTo($('#items')); }); }); 

显然,如果你知道你需要克隆和修改什么东西,你不一定需要使用recursion来获取所有东西。 但是,只要这些函数全部以正确的模式命名,就可以将这些函数重用为任意大小的嵌套结构。

这里有一个工作jsFiddle。

将数据属性添加到input以获取字段名称,用variables增加值。

html:

 <td> <input type="text" data-origin="field" name="field" id="field" required="" > <div role="button" onclick='InsertFormRow($(this).closest("tr"),"tableID","formID");' id="addrow"> + </div> </td> 

并把这个JavaScript函数

var rowNum = 1;

 var InsertFormRow = function(row, ptable, form) { nextrow = $(row).clone(true).insertAfter(row).prev('#' + ptable + ' tbody>tr:last'); nextrow.attr("id", rowNum); nextrow.find("input").each(function() { this.name = $(this).data("origin") + "_" + rowNum; this.id = $(this).data("origin") + "_" + rowNum; }); rowNum++; }