Example – Add Remove input fields dynamically using jQuery

326

Sometimes we need to adding dynamic fields in a form. For fulfill those needs, we have created a script where you can add multiple fields and remove fields easily. This script is also very useful for add multiple values in PHP. In this tutorial we will discuss about generating input fields on the fly in a form and submitting the input field’s value into the database. We have used jQuery to make this functionality very short, simple and powerful. You can add dynamic fields and remove fields easily. Also you can get the fields value in your PHP script, once the form is submitted.

Please follow the below instruction to understand our script. Also you can view the live demo from the above “Demo” link and download the full script from the “Download” link.

JavaScript:

At First include the jQuery library.

See the below JavaScript comment lines. maxField variable holding the maximum fields increment numbers, addButton variable holding the input fields adding button class, wrapper variable holding all input fields parent div class, fieldHTML variable holding new input field HTML code.

Once the “Add button” is clicked, we will check maximum input fields number. If field counter (x) is less than maxField, the new input field HTML would be append into the fields parent div (wrapper). Also the field counter would be incremented.

Once the “Remove button” is clicked, the parent div of that particular remove button would be removed. Also the field counter would be decrement.

HTML:

PHP:

Once the multiple form fields are submitted, then you can get the values as an array in PHP script.

Now you can run a foreach loop and insert the values into the database or whatever you want.

 

Leave A Reply

Your email address will not be published.