简体   繁体   中英

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>

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM