jQuery – Add/Remove Dynamic Form Fields in PHP

In this tutorial, you can add/remove dynamic form fields with the help of javaScript/jQuery. We start with single Input row and a “Add Row” button to allow user to add more rows.

When clicks on the “Add Row” button, one single row is added below the current row. You can add maximum 5 rows because limit is set only for 5 rows. Limit will change in “tgl_script.js” file.

When clicks on the “Remove Row” button, all the selected rows are deleted except one row. Clicking on the “Submit” button, All array values are captured and submitted on the next step.

Dynamic Form Processing with PHP
Dynamic Form Processing with PHP

Demo Code

Step 1 – Create Database

Create new database tgl_form_db.

Step 2 – Import Database

Import attached tgl_form_data.sql into the database tgl_form_db.

tgl_form_data.sql

CREATE TABLE IF NOT EXISTS `tgl_form_data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Add following files :-

1. index.html
2. form_submit_process.php
3. tgl_script.js
4. tgl_style.css

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Generate Dynamic Form Fields | TechGuru</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link rel="stylesheet" type="text/css" href="tgl_style.css"/>
		<script type="text/javascript" src="tgl_script.js"></script> 
    </head>
    <body>    
        <form action="form_submit_process.php" class="tgl_registration" method="POST">            
			<fieldset class="tgl_row1">
				<legend>Create Dynamic Form Using jQuery</legend>
				<p> 
					<input type="button" class="tgl_submit" value="Add Row" onClick="tgl_add_row('tgl_data_table')" /> 
					<input type="button" class="tgl_submit" value="Remove Row" onClick="tgl_delete_row('tgl_data_table')"  /> 					
				</p>
               <table id="tgl_data_table" class="form" border="1">
                  <tbody>
                    <tr>
                      <p>
						<td><input type="checkbox" required="required" name="tgl_chk[]" checked="checked" /></td>
						<td>
							<label for="tgl_name">Name</label>
							<input type="text" required="required" class="long" name="tgl_name[]">
						 </td>
						 <td>
							<label for="tgl_email">Email</label>
							<input type="email" required="required" class="long" name="tgl_email[]">
						 </td>						 
						 <td>
							<label for="tgl_gender">Gender</label>
							<select id="tgl_gender" name="tgl_gender" required="required">								
								<option value="Male">Male</option>
								<option value="Female">Female</option>
							</select>
						 </td>	
						 <td>
							<label for="tgl_age">Age</label>
							<input type="number" required="required" class="small"  name="tgl_age[]">
					     </td>					 
					  </p>
                    </tr>
                    </tbody>
                </table>
				<div class="clear"></div>
            </fieldset>
			<input class="tgl_submit" type="submit" value="Submit ยป" style="float:right;">
			<div class="clear"></div>
        </form>		
    </body>	
</html>

form_submit_process.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Post Dynamic Form Data with PHP | TechGuru</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link rel="stylesheet" type="text/css" href="tgl_style.css"/>
    </head>
    <body>    
    	<form action="" class="tgl_registration" method="post">           
			<?php if(isset($_POST) == true && empty($_POST) == false): 
				$tgl_chkbox 	= 	$_POST['tgl_chk'];				
				$tgl_name 		= 	$_POST['tgl_name'];
				$tgl_email 		= 	$_POST['tgl_email'];
				$tgl_gender 	= 	$_POST['tgl_gender'];
				$tgl_age 		= 	$_POST['tgl_age'];						
			?>
			<fieldset class="tgl_row1">
                <legend>View Dynamic Form Data</legend>				
                <table id="tgl_data_table" class="form" border="1">
					<tbody>
					<?php foreach($tgl_name as $a => $b){ ?>
						<tr>
							<p>
								<td><?php echo $a+1; ?></td>
								<td>
									<label for="tgl_name">Name</label>
									&nbsp;<input type="text" readonly="readonly" class="long" name="tgl_name[$a]" value="<?php echo $tgl_name[$a]; ?>">
								</td>
								<td>
									<label for="tgl_email">Email</label>
									&nbsp;<input type="text" readonly="readonly" class="long" name="tgl_email[]" value="<?php echo $tgl_email[$a]; ?>">
								</td>
								<td>
									<label for="tgl_gender">Gender</label>
									&nbsp;<input type="text" readonly="readonly" name="tgl_gender[]" value="<?php echo $tgl_gender[$a]; ?>">
								</td>
								<td>
									<label for="tgl_age">Age</label>
									&nbsp;<input type="text" readonly="readonly" class="small"  name="tgl_age[]" value="<?php echo $tgl_age[$a]; ?>">
								</td>					
								
							</p>
						</tr>
						<?php
						//database connection
						$username = "root";
						$password = "";
						$hostname = "localhost"; 
						$databasename = "tgl_form_db";
						
						//connect to the database
						$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
						
						//select a database to work with
						$selected = mysql_select_db($databasename,$dbhandle) or die("Could not select database");
						
						$insert_data = mysql_query("INSERT INTO tgl_form_data(name, email, gender, age)VALUES('".$tgl_name[$a]."', '".$tgl_email[$a]."', '".$tgl_gender[$a]."', '".$tgl_age[$a]."')");
					 } ?>
					</tbody>
                </table>
				<div class="clear"></div>
            </fieldset>            
		<?php else: ?>
		<fieldset class="row1">
			<legend>Sorry!</legend>
			 <p>Please try again later.</p>
		</fieldset>
		<?php endif; ?>
			<div class="clear"></div>
        </form>
    </body>	
</html>

tgl_script.js

/* Add Row */
function tgl_add_row(table_ID) {
	var table = document.getElementById(table_ID);
	var rowCount = table.rows.length;
	if(rowCount < 5){
		var row = table.insertRow(rowCount);
		var colCount = table.rows[0].cells.length;
		for(var i=0; i<colCount; i++) {
			var newcell = row.insertCell(i);
			newcell.innerHTML = table.rows[0].cells[i].innerHTML;
		}
	}else{
		 alert("Maximum 5 rows are allowed.");
			   
	}
}

/* Delete Row */
function tgl_delete_row(table_ID) {
	var table = document.getElementById(table_ID);
	var rowCount = table.rows.length;
	for(var i=0; i<rowCount; i++) {
		var row = table.rows[i];
		var chkbox = row.cells[0].childNodes[0];
		if(null != chkbox && true == chkbox.checked) {
			if(rowCount <= 1) {
				alert("Cannot remove all the rows.");
				break;
			}
			table.deleteRow(i);
			rowCount--;
			i--;
		}
	}
}

tgl_style.css

*{
    padding : 0;
    margin : 0;
    border : 0;
}

body, html{
    color : #373C40;
    font-family : Arial, Helvetica, sans-serif;
    height : 100%;
    background-color : #f0f0f0;
    margin : 10px;
}

body{
    font-size : 70%;
}

p{
    padding : 7px 0 7px 0;
    font-weight : 500;
    font-size : 10pt;
}

a{
    color : #656565;
    text-decoration : none;
}

a:hover{
    color : #4C99CC;
    text-decoration : none;
}

h1{
    font-weight : 200;
    color : #888888;
    font-size : 16pt;
    padding-left : 33px;
    margin : 8px;
}

.clear{
	width : 100%;
	float : none;
	clear : both;
}

form.tgl_registration{
    width : 800px;
    margin : 20px auto 0px auto;
    background-color : #fff;
    padding : 5px;
}

form p{
    font-size : 8pt;
    clear : both;
    margin : 0;
    color : gray;
    padding : 4px;
}

fieldset.tgl_row1{
    width : 98%;
    padding : 5px;
    float : left;
    border : 1px solid #F5F5F5;
    margin-bottom : 15px;
}

.tgl_registration .form label{
    float : left;
    text-align : left;
    margin-right : 5px;
    margin-top : 2px;
    width : auto;
}

.tgl_registration .form input{
	width : 100px;
}

.form td{
	border-right : 1px solid #F1F1F1;
	border-top : 1px solid #F1F1F1;
	border-bottom : 1px solid #F1F1F1;
	border-left : 1px solid #F1F1F1;
	padding : 2px;
	margin : 0;
}

.tgl_registration legend{
    color : #4C99CC;
    padding : 5px;
    margin-left : 14px;
    font-weight : bold;
    font-size : 14px;
    font-weight : 100;
}

.tgl_registration label{
    color : #444;
    width : 100px;
    float : left;
    text-align : right;
    margin-right : 6px;
    margin-top : 2px;
}

form.tgl_registration input{
    width : 140px;
    color : #505050;
    float : left;
    margin-right : 5px;
}

form.tgl_registration input.long{
    width : 247px;
    color : #505050;
}

form.tgl_registration input.short{
    width : 40px;
    color : #505050;
}

form.tgl_registration input[type=radio]{
    float : left;
    width : 15px;
}

form.tgl_registration label.gender{
    margin-top : -1px;
    margin-bottom : 2px;
    width : 34px;
    float : left;
    text-align : left;
    line-height : 19px;
}

form.tgl_registration input[type=text]{
    border : 1px solid #E1E1E1;
    height : 18px;
}

form.tgl_registration input[type=email]{
    border : 1px solid #E1E1E1;
    height : 18px;
}

form.tgl_registration input[type=number]{
    border : 1px solid #E1E1E1;
    height : 18px;
}

form.tgl_registration input[type=password]{
    border : 1px solid #E1E1E1;
    height : 18px;
}

form.tgl_registration input[type=button]:hover{
	cursor : pointer;
	background : #505050;
}

form.tgl_registration .tgl_submit{
    color : #fff;
    cursor : pointer;
    float : left;
    margin : 10px;
	padding : 5px;
	background : #4C99CC;
	background-image : linear-gradient(bottom,rgba(0, 0, 0, 0.1) 0,rgba(255, 255, 255, 0.1) 100%);
	background-image : -o-linear-gradient(bottom,rgba(0, 0, 0, 0.1) 0,rgba(255, 255, 255, 0.1) 100%);
	background-image : -moz-linear-gradient(bottom,rgba(0, 0, 0, 0.1) 0,rgba(255, 255, 255, 0.1) 100%);
	background-image : -webkit-linear-gradient(bottom,rgba(0, 0, 0, 0.1) 0,rgba(255, 255, 255, 0.1) 100%);
	background-image : -ms-linear-gradient(bottom,rgba(0, 0, 0, 0.1) 0,rgba(255, 255, 255, 0.1) 100%);
	background-image : -webkit-gradient(linear,left bottom,left top,color-stop(0,rgba(0, 0, 0, 0.1)),color-stop(1,rgba(255, 255, 255, 0.1)));
}

form.tgl_registration .tgl_submit:hover{
	background : #505050;
}

form.tgl_registration .tgl_submit:active{
	background : #ccc;
	color : #000;
}

form.tgl_registration input[type=text].small{
    border : 1px solid #E1E1E1;
    height : 18px;
    width : 30px;
}

form.tgl_registration input[type=number].small{
    border : 1px solid #E1E1E1;
    height : 18px;
    width : 30px;
}

form.tgl_registration input[type=checkbox]{
    width : 14px;
    margin-top : 4px;
}

form.tgl_registration select{
    border : 1px solid #E1E1E1;
    float : left;
    margin-bottom : 3px;
    color : #505050;
    margin-right : 5px;
}

input:focus, select:focus{
    background-color : #F1F1F1;
}

10 Comments on “jQuery – Add/Remove Dynamic Form Fields in PHP

  1. What’s up to all, how is everything, I think every one is getting more from this web page, and your views are pleasant designed for new users.

  2. Hi there! I could have sworn I’ve been to this
    site before but after going through many of the articles I realized it’s new to me.
    Nonetheless, I’m certainly delighted I found it and I’ll be book-marking it and
    checking back regularly!

  3. Fantastic goods from you, man. I have bear in mind your
    stuff previous to and you’re simply extremely excellent. I really like what you’ve acquired here,
    really like what you’re stating and the way during which you are
    saying it. You are making it enjoyable and you still take care of to stay it sensible.
    I can not wait to read much more from you. This is actually a
    great web site.

Leave a Reply

Your email address will not be published.

*