Dynamically add fields using php & jquery

In this tutorial, i will explain how to add and remove form input fields dynamically using jQuery. I will show you full working of example of how to add and remove input fields and submit to database with jquery ajax and php where you cam see add more fields in the demo.

Dynamic input fields allows providing multiple inputs in a form where this feature can be easily integrated using jQuery. You can add multiple fields and remove fields easily.

Dynamically add fields using php & jquery

If you’re developing web application where multiple input fields are needed then you came to right place and this tutorial will be useful.

So here you have to just follow few steps to proceed.

In order to start, we must have following file structure.

  • index.php
  • adder.js
  • poster.php
  • Step 1: Create an index.php file

    Firstly, we have to create a form with a post action in it.

    <form action="poster.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"/>

    Step 2: Write javascript function to input forms dynamically.

    When we click on plus icon then new input box will be created and when we click on minus icon input box will be deleted, for this functionality we are writing the code in adder.js file.

        var max_fields = 15;
        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){

    If you can see, we limited the maximum inputs to 15 in the javascript i.e var max_fields = 15, where the input fields will not exceed more than 15 fields.

    Step 3:

    Handling the form submit in the server end by using php and jquery and display the values in array.
    In the above example we are not linking fields in database we are just adding the fields and their values in poster.php. From this file you can integrate the values accordingly in to your database.

    <div class="container">
    	<h2>Example: Add Fields Dynamically using jQuery and PHP</h2>		
    		print '<pre>';
    		print '</pre>';
    	<div style="margin:10px 0px 0px 0px;">
    		<a class="btn btn-default read-more" style="background:#3399ff;color:white" href="https://www.codenap.com/" title="">Back</a>			

    That’s it, you can view the working example of demo.

    Demo Download

    Leave a Reply