我克隆了一个表单,但它也是一个输入值。这是表格html
<form role="form" method="post" action="<?php echo base_url(); ?>staff_activity/add_ftth" enctype="multipart/form-data" >
<div id="main">
<div class="col-md-12">
<div class="form-group col-md-4">
<label>Client's Name</label>
<input type="text" class="form-control" name="client_name[]" placeholder="Client's Name" id="client_name" autofocus required/>
</div>
<div class="form-group col-md-4">
<label>Phone Number</label>
<input type="text" class="form-control" name="phone_number[]" placeholder="Phone Number" id="phone_number"/>
</div>
<div class="col-md-4">
<label>Package</label>
<select class="form-control" name="package[]" >
<option selected="">
</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group col-md-6">
<label>Remarks</label>
<textarea name="remarks[]" class="form-control" placeholder="remarks" ></textarea>
</div>
</div>
</div>
<div class="col-md-12 buttonbox">
<div class="pull-left">
<button type="button" class="btn btn-success add" >ADD +</button>
<button type="button" class="btn btn-danger remove" >DEL -</button>
</div>
</div>
<div class="col-md-12">
<div class="pull-right">
<input type="submit" class="btn btn-success btn-xm submit" name="submit" value="Submit" />
</div>
</div>
</form>
我的克隆脚本如下
$(document).ready(function() {
var i = 0;
var last12 = $('.buttonbox').last();
$(document).on('click', '.add', function() {
var clone = $('#main').last().clone().attr("id", "main" + i++).insertBefore(last12);
//clone.id = "main" + i;
});
$(".remove").click(function(){
$("#main:last").remove();
});
});
在克隆分部时,表格值也被克隆。 您可以在JSFiddle中检查此代码。 https://jsfiddle.net/szn0007/yoebgocq/
答案 0 :(得分:4)
尝试以下操作:使用val('')
重置输入和textarea用于选择我们将选择select中的第一个元素(默认值)
var clone = $('#main').clone().find("input,textarea").val("").end().find('select option:first-child()').attr('selected','selected').end().attr("id", "main" + i++).insertBefore(last12);
删除使用:
$(".remove").click(function(){
$('div[id^="main"]:last').remove();
});
答案 1 :(得分:1)
更新
$(function(){
var i = 0;
var last12 = $('.buttonbox').last();
$(document).on('click', '.add', function() {
var clone = $('#main').clone();
clone.find("input").val("");
clone.find("textarea").val("");
clone.find('select option:first-child()');
clone.attr("id", "main" + i++).insertBefore(last12);
//clone.id = "main" + i;
});
$(".remove").click(function(){
$('.main:last').remove();
});
});
for refrence https://plnkr.co/edit/EvOaLL1mQYB8yf6NDpby?p=preview
答案 2 :(得分:0)
好吧
对我来说,最简单的方法是:
var last12 = $('.buttonbox').last(),
newForm = $("#theFormToClone")[0].cloneNode(true);
newForm.innerHTML = newForm.innerHTML;
$(newForm).insertBefore(last12)
最诚挚的问候。