June 9, 2016
jQuery Add & Remove Dynamically Input Fields in PHP

Hi, friends in this tutorial I show you how to add & remove dynamically input fields with jQuery & PHP. We need to add and remove dynamic fields in a form. For fulfilling those requirements, we have created a simple script where you can add many fields and remove fields. This script is also very helpful for add multiple values in PHP. Now we are going to generate input fields in a form and submitting the input field’s value into the database.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<html> <head> <title>jQuery Add & Remove Dynamically Input Fields in PHP</title> </head> <body> <h1>jQuery Add & Remove Dynamically Input Fields in PHP</h1> <form name="add_me" id="add_me"> <table id="dynamic"> <input type="text" name="name[]" placeholder="Enter Your Name" /> <button type="button" name="add" id="add_input">Add</button> </table> <input type="button" name="submit" id="submit" value="Submit" /> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script> <script> $(document).ready(function() { var i = 1; $('#add_input').click(function() { i++; $('#dynamic').append('<tr id="row' + i + '"><td><input type="text" name="name[]" placeholder="Enter Your Name"/></td><td><button type="button" name="remove" id="' + i + '" class="btn_remove">Remove</button></td></tr>'); }); $(document).on('click', '.btn_remove', function() { var button_id = $(this).attr("id"); $('#row' + button_id + '').remove(); }); $('#submit').click(function() { $.ajax({ url: "insert.php", method: "POST", data: $('#add_me').serialize(), success: function(data) { alert(data); $('#add_me')[0].reset(); } }); }); }); </script> </body> </html> |
insert.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $conn = mysqli_connect("localhost", "root", "", "test"); $number = count($_POST["name"]); if($number > 0) { for($i=0; $i<$number; $i++) { if(trim($_POST["name"][$i] != '')) { $sql = "INSERT INTO info(name) VALUES('".mysqli_real_escape_string($conn, $_POST["name"][$i])."')"; mysqli_query($conn, $sql); } } echo "Data Inserted Successfully"; } else { echo "Enter Your Name"; } ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]