how to add multiple input fields dynamically in javascript and PHP?

Today, We want to share with you dynamically add input fields and submit to database with javascript and php.In this post we will show you add/remove multiple input fields dynamically with javascript, hear for add/remove input fields dynamically with javascript we will give you demo and example for implement.In this post, we will learn about Add Field Dynamically To Form In Jquery And Php with an example.

how to add dynamic textbox (row) and save to database using php?

Step 1: Create Database and Table

SQL Query:

--
-- Database: `pakainfo_v1`

-- Table structure for table `visitors`
--

CREATE TABLE `visitors` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `visitors`
--

INSERT INTO `visitors` (`id`, `name`, `email`) VALUES
(1, 'rohitsharama', '[email protected]'),
(2, 'bhavika dema', '[email protected]'),
(3, 'mayur', '[email protected]'),
(4, 'dipti', '[email protected]'),
(5, 'rakhi', '[email protected]');

Step 2 : Create Database connection with MySQL

config.php

<?php
	// Database configuration 
	$hostname = "localhost"; 
	$username = "root"; 
	$password = ""; 
	$dbname   = "pakainfo_v1"; 
	 
	// Make database connection 
	$conn = mysqli_connect($hostname, $username, $password, $dbname); 
	 
	// here Check connection
	if(mysqli_connect_errno()) {
	  echo "Failed to connect to MySQL: " . mysqli_connect_error();
	  exit();
	}

?>

Step 3 : Create HTML File index page, jQuery & AJAX

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Dynamic add/remove input fields in PHP Jquery AJAX - www.pakainfo.com</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>

<div class="card text-center" style="margin-bottom:50px;">
  <h2>Dynamic Add/Remove input fields in PHP Jquery AJAX - www.pakainfo.com</h2>
</div>
  
<div class="dsp container">
  <div class="row">
    <div class="col-md-1"></div>
      <div class="col-md-10">
        <div class="form-group">
          <form name="add_name" id="add_name">
            <table class="table table-bordered table-hover" id="add_more_visitor">
              <tr>
                <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
                <td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
                <td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>  
              </tr>
            </table>
            <input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
          </form>
        </div>
      </div>
    <div class="col-md-1"></div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

<script type="text/javascript">
  $(document).ready(function(){

    var i = 1;

    $("#add").click(function(){
      i++;
      $('#add_more_visitor').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list"/></td><td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
    });

    $(document).on('click', '.btn_remove', function(){  
      var button_id = $(this).attr("id");   
      $('#row'+button_id+'').remove();  
    });

    $("#submit").on('click',function(){
      var formdata = $("#add_name").serialize();
      $.ajax({
        url   :"action.php",
        type  :"POST",
        data  :formdata,
        cache :false,
        success:function(result){
          alert(result);
          $("#add_name")[0].reset();
        }
      });
    });
  });
</script>

Step 4 : Create PHP server side code file

action.php

<?php

	include_once('config.php');

	$visitorData = count($_POST["name"]);
	
	if ($visitorData > 0) {
	    for ($i=0; $i < $visitorData; $i++) { 
		if (trim($_POST['name'] != '') && trim($_POST['email'] != '')) {
			$name   = $_POST["name"][$i];
			$email  = $_POST["email"][$i];
			$query  = "INSERT INTO visitors (name,email) VALUES ('$name','$email')";
			$result = mysqli_query($con, $query);
		}
	    }
	    echo "Data inserted successfully";
	}else{
	    echo "Please Enter visitor name";
	}

?>

I hope you get an idea about duplicate or add more form input group with jquery and php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.