更新时间:2023-12-05 21:58:58
对于多行,请使用"main_section"之类的类代替id.然后单击添加主要"按钮时,使用 $(this).parent().prev() ".
For multiple row use class like 'main_section' instead of id. and when click on 'Add Main' button append the clone to the immediately preceding sibling 'main_section' using $(this).parent().prev()'.
将是主要部分的jQuery代码.
jQuery code for main section will be.
jQuery(function($){
var unique_id = 0;
var appendto = '';
jQuery(document).on('click', 'button.click', function(){
var appendto = $(this).parent().prev();
$(this).parent().prev().find(".row1:first").clone().find("input,select").each(function() {
-----
}).end().appendTo(appendto);
完整代码.
Complete code.
jQuery(function($){
var unique_id = 0;
jQuery('.sectionClick').on('click', function(){
$(".section .row2:first").clone().find("h4,div,input,select").each(function() {
this.name = $(this).attr("name")+"_"+unique_id; //make name unique of new row
this.id = $(this).attr("id")+"_"+unique_id; // make id unique of new row
this.value = ''; //make value empty of new row
var fieldName = $(this).attr('name');
$(this).siblings().attr('for', fieldName);
}).end().appendTo(".section").find('.row1').not(':first').remove(); //append only first row, remove other
unique_id++;
});
});
jQuery(function($){
var unique_id = 0;
var appendto = '';
jQuery(document).on('click', 'button.click', function(){
var appendto = $(this).parent().prev();
$(this).parent().prev().find(".row1:first").clone().find("input,select").each(function() {
this.name = $(this).attr("name")+"_"+unique_id; //make name unique of new row
this.id = $(this).attr("id")+"_"+unique_id; // make id unique of new row
this.value = ''; //make value empty of new row
var fieldName = $(this).attr('name');
$(this).siblings().attr('for', fieldName);
}).end().appendTo(appendto);
unique_id++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div class="container-fluid section">
<div class="row2">
<h4>
Section Details
</h4>
<div id="main" class="main_section">
<div class="row1">
<div class="control-group">
<label for="caption">caption</label>
<input name="caption" id="caption" type="text">
</div>
</div>
</div>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-space main click">Add Main</button>
</div>
</div>
</div>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-space sectionClick">Add Another Section</button>
</div>