克隆表单,添加新的每个 [英] Clone form, add new each one
本文介绍了克隆表单,添加新的每个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我点击按钮时,我需要逐个添加表格,但在第二次点击时,该功能会附加多个表格。
I need to add one by one form when I click the button, but in the second click the function appends more than one form.
我做错了什么在我的脚本中?
What am I doing wrong in my script?
谢谢
$('.add-more-btn').click(function() {
var clone = $('.form-main').clone('.form-block');
var block = $('.form-block')
$(block).append(clone);
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title>Clone forms</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<form class="form-main">
<div class="form-block">
<div class="form-group">
Name
<input type="text" name="name[]" class="form-control">
</div>
<div class="form-group">
Email
<input type="text" name="email[]" class="form-control">
</div>
<hr>
</div>
</form>
<a class="btn btn-primary add-more-btn">Add one</a>
</div>
</div>
</div>
推荐答案
您想要复制 .form-block
并将其附加到< form>
...
首先正确识别元素......要克隆的形式和元素。
You want to duplicate the .form-block
and append it to the <form>
...
So identify the elements correctly first... The form and the element to be cloned.
然后, .clone()
单击模板。
Then, .clone()
from a stored "template" on click.
请注意,您必须克隆模板...再次点击!
Notice that you have to clone for the "template"... And again on click!
var template = $(".form-block").clone();
var form = $(".form-main");
$('.add-more-btn').on('click',function() {
var newFormBlock = template.clone(); // Clone again here, to be able to append more than once.
form.append(newFormBlock);
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title>Clone forms</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<form class="form-main">
<div class="form-block">
<div class="form-group">
Name
<input type="text" name="name[]" class="form-control">
</div>
<div class="form-group">
Email
<input type="text" name="email[]" class="form-control">
</div>
<hr>
</div>
</form>
<a class="btn btn-primary add-more-btn">Add one</a>
</div>
</div>
</div>
这篇关于克隆表单,添加新的每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文