PHP

Add Remove Input Fields Dynamically using jQuery

Pinterest LinkedIn Tumblr

Step 1: Create Database Table

CREATE TABLE `info` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Create index.php File

<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: "insertdata.php",
                    method: "POST",
                    data: $('#add_me').serialize(),
                    success: function(data) {
                        alert(data);
                        $('#add_me')[0].reset();
                    }
                });
            });
        });
    </script>
</body>
 
</html>

Step 3: Create insertdata.php File

<?php

$conn = mysqli_connect("localhost", "root", "root", "dyanmic");
$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";
}
?>

Write A Comment

Open chat
Hey Visitor,

How can I help you?