Reputation: 73
Removing div element automatically after appending it on click. It removes the element after it adds or appends inside form tag.
$('.add').on('click', function() {
$('#testAdd').append('<div class="form-group add-input"> <input type="text" placeholder="add someting..."> <button class="add">+</button> </div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testAdd" action="" method="POST">
<div class="form-group add-input">
<input type="text" placeholder="add someting...">
<button class="add">+</button>
</div>
</form>
Upvotes: 4
Views: 1131
Reputation: 2584
add type="button"
to existing button tag and work well and not submitting while clicking on it.
$('.add').on('click', function() {
$('#testAdd').append('<div class="form-group add-input"> <input type="text" placeholder="add someting..."> <button type="button" class="add">+</button> </div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testAdd" action="" method="POST">
<div class="form-group add-input">
<input type="text" placeholder="add someting...">
<button type="button" class="add">+</button>
</div>
</form>
Upvotes: 3
Reputation: 72175
After clicking on the +
button the <div>
element is appended to the form as expected. But then the form is submitted to the server. When the page reloads the html of the page is rendered again and thus the appended <div>
element dissappears.
You can change the type of the button like this
<button type="button" class="add">+</button>
and add another button for sumitting the form.
Upvotes: 3