POSTED IN Javascript Jquery

Add or remove form inputs dynamically using jquery

Add or remove form inputs dynamically using jquery

Some places we need to adding or cloning the form fields dynamically. By default we have Jquery clone() function. Which will clone the particular mentioned div or element and insert to mentioned places. Its simple and useful for cloning one field. If you want to clone group of elements and customising is little difficult.

Here we are going to see how to Dynamically add or remove form inputs using jquery. Here we can customise the form fields how ever we want.

1. Create Index.php file

2. Create From Inputs (Which you want to clone) alone in another file(clone-form.php)

3. Use Jquery load() function to add or remove form inputs.

4. Create a php from action file to retrieve user inputs.

My Index.php

1. Here I have mentioned the $length is 1. Beacause On create time we must have minimum one form group. In update page you can change the length based on user cloned forms on create time

2. Included clone-form.php which contains form elements

3. I set $_REQUEST[‘id’]=$i; Because during clone time We will pass parameter Id to clone-form.php. By same way here we have assigned parameter id as $i.

4. Have added 2 hidden input boxes. A. length (Count of Inserted forms on page load) B. last_inserted_id(Count of Inserted forms on page load minus 1 ) Its going to help us during the clone time.


Here Based on $i values we will form the array of input elements.

In my index.php I have called addAnotherBlock() function to add new set of block

You can see I have added id “last_inserted_id_<?php $i ?>” every end of block. Because Based on end of block we will load another set of elements.
This function will load load clone-form.php based on passing parameter.

On first click length will be total loaded from groups count and length++ will increase the value. On next click will pass increased value and so on.

Based on this logic you can modify or customise any number form elements and can convert as our need.

On submit it will redirect to query.php page



Lets see how to extract user inputs in php


Here formdata  is the primary array name of all inputs. Based on foreach we can extract all inputs as aobe.

Hope it will help someone.