Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an element on click in jQuery

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>
like image 961
Saani Info Avatar asked Nov 15 '25 17:11

Saani Info


1 Answers

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.

like image 117
Giorgos Betsos Avatar answered Nov 18 '25 09:11

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!