4

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>

2
  • 3
    button type should be button, by default it's submitting the form Commented Dec 24, 2020 at 6:41
  • @AbhishekPandey I also agree with you! Commented Dec 24, 2020 at 6:49

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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>

3 Comments

you are missing button type in JS
clicking on newly added buttons will submit page
Use $(document).on('click','.add', function() instead of $('.add').on('click', function()to add click support for JS appended buttons

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.