Dynamically Add Remove input fields in PHP

How to Dynamically Add Remove input fields in PHP with Jquery Ajax?

How to Dynamically Add Remove input fields in PHP

In this tutorial, we will learn How to Dynamically Add Remove input fields in PHP with Jquery Ajax and insert, update or delete data into the database. In this PHP module, users can insert, update or delete more than one record at a time in the MySql database.

Now, these days Dynamically Add Remove input fields are very useful functionality for any web application.

Dynamically Add Remove input fields

So in this module user can add more input fields (Item Quantity (in pieces) Weight (in quintal) Rate (per quintal) Price) by clicking on Add a Row button than new Item Quantity (in pieces) Weight (in quintal) Rate (per quintal) Price will be added to the webpage. Users can also remove the input fields by clicking on the remove button (X) which is available on the left side. 

Read Also:

  1. Pricing Table Design Bootstrap 5?
  2. How to Display Content on hovering Card using CSS?
  3. How to create a Portfolio Gallery?
  4. FAQ Page with Show and Hide Questions and Answers?
  5. Bootstrap Team Section Design Download
  6. Bootstrap Carousel with Captions and Thumbnails Free Download
  7. Bootstrap Table Search Filter Free Download

Steps to create Dynamically Add Remove input fields

  1. Create index.php
  2. Create addRowCode.php
  3. Create dbconnect.php
  4. Create delete_member.php
  5. Create editRow.php

Library File

We have to add the following jQuery and the Bootstrap library in the head section of the page.

<script  src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
<script type='text/javascript' src='js/example.js'></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" rel="stylesheet" >

Database Table

CREATE TABLE IF NOT EXISTS `dynamicrow` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ItemName` varchar(500) NOT NULL,
  `quantity` varchar(100) NOT NULL,
  `weight` varchar(100) NOT NULL,
  `rate` varchar(100) NOT NULL,
  `price` varchar(500) NOT NULL,
  `status` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=65 DEFAULT CHARSET=latin1;

HTML Code

First, we need to create an index.php. This section will help you to create the structure of Dynamically Add Remove input fields, Add a row and Delete button.

<div class="container">
  <div class="row">
    <div class="col-md-2 mt-3"> <img src="https://htmlcss3tutorials.com/wp-content/themes/htmlcss3TutorialRevamp/assets/img/logo/html-logo.png" alt="HTML CSS3 Tutorials" style="width:100%;" /> </div>
  </div>
  <div class="row">
    <div class="col-md-12 mt-5 mb-5 text-center">
      <h2>Dynamically Add / Remove input fields in PHP</h2>
    </div>
    <div class="col-md-10">
      <?php
      if ( isset( $errMSG ) ) {
        ?>
      <div class="alert alert-danger alert-dismissible fade show" role="alert"> <?php echo $errMSG;
      ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div >
      <?php
      } else if ( isset( $successMSG ) ) {
        ?>
      <div class="alert alert-success alert-dismissible fade show" role="alert"> <?php echo $successMSG; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
      <?php
      }

      ?>
      <form class="form-horizontal" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" >
        <table id="items" class="table table-striped table-hover">
          <tr>
            <th>Item</th>
            <th>Quantity (in peices)</th>
            <th>Weight (in quintal)</th>
            <th>Rate (per quintal)</th>
            <th>Price</th>
          </tr>
          <tr class="item-row">
            <td class="item-name"><input name="ItemName[]" placeholder="Item Name" class="cust" required="required" /></td>
            <td ><input name="quantity[]" id="quantity" placeholder="Quantity"  class="quantity" required="required" /></td>
            <td><input type="text"  name="weight[]" id="qty" class="qty"  placeholder="Weight" required="required"></td>
            <td><input type="text"  name="rate[]" id="cost" class="cost" placeholder="Rate"  required="required"></td>
            <td><input type="text"  name="price[]" class="price" placeholder="Price" required="required"></td>
          </tr>
          <tr>
            <td colspan="4" class="blank"><a id="addrow" href="javascript:;" title="Add a row" class="btn btn-warning"><i class="fas fa-plus-circle"></i> Add a row</a></td>
            <td><button name="submit" id="submit" class="btn btn-success" />
              <i class="fas fa-arrow-alt-circle-up"></i> Submit
              </button></td>
          </tr>
        </table>
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-md-10">
      <table class="table table-striped table-hover">
        <tr>
          <th>Item</th>
          <th>Quantity (in peices)</th>
          <th>Weight (in quintal)</th>
          <th>Rate (per quintal)</th>
          <th>Price</th>
          <th>Action</th>
        </tr>
        <?php
        $result = $DB_con->prepare( "SELECT * FROM dynamicrow where status=2 ORDER BY id Desc" );
        $result->execute();
        for ( $j = 0; $row = $result->fetch(); $j++ ) {
          ?>
        <tr class="delete_mem<?php echo $row['id']; ?>">
          <td><?php echo $row['ItemName']; ?></td>
          <td ><?php echo $row['quantity']; ?></td>
          <td><?php echo $row['weight'] ; ?></td>
          <td><?php echo $row['rate'] ; ?></td>
          <td><?php echo $row['price'] ; ?></td>
          <td><a href="editRow.php?Token=<?php echo $row['id']; ?>"><i class="fas fa-edit"></i></a> | <a href="#" id="<?php echo $row['id']; ?>" class="trash"><i class="fas fa-trash-alt" style="color: #b60000;"></i></a>
        </tr>
        <?php

        }
        ?>
      </table>
    </div>
  </div>
</div>

addRowCode

<?php //error_reporting( ~E_NOTICE ); // avoid notice
require_once 'dbconnect.php';
if ( isset( $_POST[ 'submit' ] ) ) {
  $ItemName = implode( ",", $_POST[ 'ItemName' ] );
  $quantity = implode( ",", $_POST[ 'quantity' ] ); // in pieces
  $weight = implode( ",", $_POST[ 'weight' ] ); // weight in quintal
  $rate = implode( ",", $_POST[ 'rate' ] ); //rate per quintal
  $price = implode( ",", $_POST[ 'price' ] );
  $status = 2;
  if ( empty( $ItemName ) ) {
    $errMSG = "Please Enter Item Name";
  } else if ( empty( $quantity ) ) {
    $errMSG = "Please Enter Quantity";
  } else if ( empty( $weight ) ) {
    $errMSG = "Please Enter Cost.";
  } else if ( empty( $rate ) ) {
    $errMSG = "Please Enter Cost.";
  }
  if ( !isset( $errMSG ) ) {
    $stmt = $DB_con->prepare( 'insert into dynamicrow (ItemName,quantity,weight,rate,price,status) VALUES(:ItemName1, :quantity1, :weight1,:rate1, :price1,:status1)' );
    $stmt->bindParam( ':ItemName1', $ItemName );
    $stmt->bindParam( ':quantity1', $quantity );
    $stmt->bindParam( ':weight1', $weight );
    $stmt->bindParam( ':rate1', $rate );
    $stmt->bindParam( ':price1', $price );
    $stmt->bindParam( ':status1', $status );
    if ( $stmt->execute() ) {
      $successMSG = "Record inserted Successfully..";
      //header( "Location: index.php" );
    } else {
      $errMSG = "error while inserting....";

    }
  } else {
    $errMSG = "OOPS! Something went wrong....";
  }
}
?>

jQuery Ajax Code

<script  src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
<script type='text/javascript' src='js/example.js'></script> 
<script type="text/javascript">
	$(function(){
    $(document).on('click','.trash',function(){
        var del_id= $(this).attr('id');
        var $ele = $(this).parent().parent();
		if(confirm("Are you sure want to remove this data?")){
        $.ajax({
            type:'POST',
            url:'delete_member.php',
            data:{'del_id':del_id},
            success:function(html){
		$(".delete_mem" + del_id).fadeOut('slow');
             }

            });
		}else{
		return false;	
		}
        });
});

</script> 
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ></script>

Edit Page Code

Add or remove input fields dynamically in PHP using jQuery

This section will help you to create the edit page.

<?php //error_reporting( ~E_NOTICE ); // avoid notice
error_reporting(1);
require_once 'dbconnect.php';
$authToken = $_GET[ 'Token' ];
if ( isset( $_POST[ 'submit' ] ) ) {
  $id = $_POST[ 'id' ];
  $ItemName = implode( ",", $_POST[ 'ItemName' ] );
  $quantity = implode( ",", $_POST[ 'quantity' ] ); // in pieces
  $weight = implode( ",", $_POST[ 'weight' ] ); // weight in quintal
  $rate = implode( ",", $_POST[ 'rate' ] ); //rate per quintal
  $price = implode( ",", $_POST[ 'price' ] );

  if ( empty( $ItemName ) ) {

    if ( empty( $ItemName ) ) {
      $errMSG = "Build Name field is empty.";
    }

  } else {

    $sql = "UPDATE dynamicrow set ItemName=:ItemName,quantity=:quantity,weight=:weight, rate=:rate,price=:price WHERE id=:id";
    $stmt = $DB_con->prepare( $sql );
    $stmt->bindParam( ':id', $id );
    $stmt->bindParam( ':ItemName', $ItemName );
    $stmt->bindParam( ':quantity', $quantity );
    $stmt->bindParam( ':weight', $weight );
    $stmt->bindParam( ':rate', $rate );
    $stmt->bindParam( ':price', $price );
    if ( $stmt->execute() ) {
      $successMSG = "Record has been updated Successfully..";
		header( "Location: index.php" );
    } else {
       $errMSG ="error while updating....";

    }
  }
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dynamically Add / Remove input fields in PHP</title>
<link rel='stylesheet' type='text/css' href='css/style.css' />
<script  src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
<script type='text/javascript' src='js/example.js'></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" rel="stylesheet" >
</head>

<body>
<div class="container">
  <div class="row">
    <div class="col-md-12 mt-5 mb-5 text-center">
      <h2>Dynamically Add / Remove input fields in PHP</h2>
    </div>
    <div class="col-md-10">
      <?php
      if ( isset( $errMSG ) ) {
        ?>
      <div class="alert alert-danger alert-dismissible fade show" role="alert"> <?php echo $errMSG;
      ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div >
      <?php
      } else if ( isset( $successMSG ) ) {
        ?>
      <div class="alert alert-success alert-dismissible fade show" role="alert"> <?php echo $successMSG; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
      <?php
      }

      ?>
      <?php
      $stmt_edit = $DB_con->prepare( "SELECT * FROM dynamicrow where id ='$authToken'" );
      $stmt_edit->execute();
      $edit_row = $stmt_edit->fetch( PDO::FETCH_ASSOC );
      extract( $edit_row );

      ?>
      <form class="form-horizontal" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" >
        <table id="items" class="table table-striped table-hover">
          <tr>
            <th>Item</th>
            <th>Quantity (in peices)</th>
            <th>Weight (in quintal)</th>
            <th>Rate (per quintal)</th>
            <th>Price</th>
          </tr>
          <?php
          $a = explode( ",", $edit_row[ 'ItemName' ] );
          $ItemName = explode( ",", $edit_row[ 'ItemName' ] );
          $quantity = explode( ",", $edit_row[ 'quantity' ] );
          $weight = explode( ",", $edit_row[ 'weight' ] );
          $rate = explode( ",", $edit_row[ 'rate' ] );
          $price = explode( ",", $edit_row[ 'price' ] );
          $NoItem = $a;
          for ( $i = 0; $i < count( $NoItem ); $i++ ) {
            $ItemNameF = $ItemName[ $i ];
            $quantityF = $quantity[ $i ];
            $weightF = $weight[ $i ];
            $rateF = $rate[ $i ];
            $priceF = $price[ $i ];
            ?>
          <tr class="item-row">
            <td class="item-name"><div class="delete-wpr">
				<input type="hidden" name="id"  value="<?php echo $edit_row['id']; ?>">
                <input name="ItemName[]" value="<?php echo $ItemNameF; ?>" class="cust" />
                <a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
            <td class="description"><input name="quantity[]" id="quantity" value="<?php echo $quantityF; ?>"  class="quantity" /></td>
            <td><input type="text"  name="weight[]" id="qty" class="qty" value="<?php echo $weightF; ?>" ></td>
            <td><input type="text"  name="rate[]" id="cost" class="cost" value="<?php echo $rateF; ?>"></td>
            <td><input type="text"  name="price[]" class="price" value="<?php echo $priceF; ?>" required="required"></td>
          </tr>
          <?php } ?>
          <tr>
            <td colspan="4" class="blank"><a id="addrow" href="javascript:;" title="Add a row" class="btn btn-warning"><i class="fas fa-plus-circle"></i> Add a row</a></td>
           <td><button name="submit" id="submit" class="btn btn-success" /><i class="fas fa-arrow-alt-circle-up"></i> Update</button></td>
          </tr>
			<tr>
            <td colspan="5" class="blank"><a href="addRow.php" class="btn btn-primary"><i class="fas fa-arrow-circle-left"></i> Back</a></td>
          </tr>
        </table>
      </form>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ></script>
</body>
</html>

Delete Page Code

<?php
require_once 'dbconnect.php';
$id = $_POST[ "del_id" ];
$status = 9;
$sql = "UPDATE dynamicrow set status=:status  WHERE id=:id";
$stmt = $DB_con->prepare( $sql );
$stmt->bindParam( ':id', $id );
$stmt->bindParam( ':status', $status );
if ( $stmt->execute() ) {
   $MSG = "Are you sure want to remove this data?";
} else {
   $MSG = "error while updated....";
}

?>
Dynamically add remove input fields in PHP with Jquery Ajax

Database Connection

$servername = "localhost";
$username = "root";
$password = "";

try {
  $DB_con = new PDO("mysql:host=$servername;dbname=grabogec_aabills", $username, $password);
  // set the PDO error mode to exception
  $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

Conclusion

Hope this tutorial will help you to create the Dynamically Add Remove input fields.

Read Also:

  1. Circle Progress Bar Using HTML CSS3
  2. Responsive HTML Menu Free Download
  3. Owl Carousel Slider Bootstrap 5