Add Fields Dynamically using jQuery and PHP

Add Fields Dynamically using jQuery and PHP

Add and remove dynamic input fields is an important feature of web applications. It allows user friendly feature to add and remove form input dynamically to increases user experience. If you're developing a web application wants to add this feature then you're here at right place. In this tutorial you will learn how to add and remove form input fields dynamically using jQuery.
You will also learn to handle dynamically added fields value saves in database using PHP. The tutorial covered in very easy steps with live Demo and complete source code to download.

So let’s start the coding. We will have following file structure for this tutorial.

  • index.php

  • add_fields.js

  • form_post.php

Steps1: Create Form with Add Field Buuton
In index.php, we will Form HTML add field button to add fields dynamically.
<form action="post_form.php" method="post">
<div class="field_wrapper">
<input type="text" name="input_field[]" value=""/>
<a href="javascript:void(0);" class="add_input_button" title="Add field"><img src="add-icon.png"/></a>
<input type="submit" name="save" value="Submit"/>

Steps2: JavaScript to Form Input Fields Dynamically
In add_fields.js , we will handle functionality to add input fields dynamically on button click. Also handle functionality to remove added input fields.
var max_fields = 10;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var new_field_html = '<div><input type="text" name="input_field[]" value=""/><a href="javascript:void(0);" class="remove_input_button" title="Remove field"><img src="remove-icon.png"/></a></div>';
var input_count = 1;
// Add button dynamically
if(input_count < max_fields){
// Remove dynamically added button
$(field_wrapper).on('click', '.remove_input_button', function(e){

Steps3: Handle From Submit Value At Server End
Now finally in form_post.php, we will handle form submit input field value using PHP. You can add functionality to save Form values to database.
print '<pre>';
print '</pre>';

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

You may like these posts