Nowadays we always try to make our site more and more dynamic and user preferable. That’s why we use some client side programming like jQuery, JavaScript etc. Now if you want to add some input field dynamically and remove it dynamically then you need to use jQuery. By using jQuery you can add multiple input field in a form and if you don’t want the extra input field, then remove it using a button.
In this tutorial I will help you to append input field dynamically in your web application with an example of source code which is given in the below of this tutorial.
You need to add the jQuery cdn or jQuery file path inside the head tag. If you wouldn’t do this then you can not access jQuery library. You can use this code, when you will insert multiple data into the database using jQuery.
Example And Source Code:
<!DOCTYPE html> <html lang="en"> <head> <title>My Web Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <table id="table_id"> <tr> <td><input type="text" name="name"></td> <td><button class="btn btn-success" id="addfield">Add New Field</button></td> </tr> </table> <script type="text/javascript"> $(document).ready(function(){ var i=1; $("#addfield").click(function(){ i++; $("#table_id").append('<tr id="t_id'+i+'"><td><input type="text" name="name"></td><td><button class="btn btn-danger remove_field" id="'+i+'">Remove Field</button></td></tr>'); }); $(document).on('click','.remove_field',function(){ var remove_id=$(this).attr("id"); //alert(remove_id); $("#t_id"+remove_id+"").remove(); }); }); </script> </div> </div> </body> </html>
So let’s start this code in your web application and add multiple input field in your submit form using jQuery.
Thanks, good Post.
Such a nice article, Thank for help.