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?
Thanks
$('.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>
Because using the clone method on a css class every div container with the css class
.form-block
is cloned. As you add another block with the css class.form-block
you 've got two blocks with the same class name. On the next click you clone two items and so on.Why not using the HTML5 template tag. Using this native type of templating you can archive several advantages. Your form will be faster, because you don 't need to load the jQuery library. With a few lines of native JavaScript you can archive, what you want. Have a look at the following example.
This is an html example so far. You can add your own input elements and styles here. This piece of code is just for example purposes.
Now it 's time for some native JavaScript.
This works on every modern browser. For more detals about the html5 template tag and its functionality have a look at the MDN Web Docs. Also have a look at caniuse.com to see the browser support. As you can see, Microsofts Internet Explorer 11 does not support the template tag and its functionality. For that there are some astounding polyfills like the Web Components small template polyfill you could use, when IE11 support is in need.
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.
Then,
.clone()
from a stored "template" on click.Notice that you have to clone for the "template"... And again on click!
Do not clone on button click. It is cloning what is in the form at the time of click which is increasing with every click. Instead, clone the form on load and store it in a variable. Then use it as many times.
And note that .clone() does not take the parameter you were passing.
Another solution with
html
which copy the first set of element.