Dynamically Adding Form Elements in JQuery

In my last project, my client wanted the ability to add multiple form elements to their existing forms.  This was relatively easy using JQuery and JavaScript. This tutorial will show you how to dynamically add, delete and save the form elements.

The Code

First things is to build out the HTML file with a form.

This is the output from the HTML above. Note that the ‘save button’ does not show because I didn’t want the user to click on the button with nothing to save.

When the document loads it hides the save button and initializes a counter variable called ‘x’. This counter keeps track of how many form elements there are.

When the user clicks on the ‘add row’ button it appends a first name, last name and a delete button.

Below shows that I’m appending a new form element to the div named ‘input_wrapper’.

HTML view

For the delete functionality, every time the user clicks on a delete button, I’m targeting the button’s class, ‘deleteBtn’. From that click, I can get access to the event object. In that event object, I can look for the id which is the counter, ‘x’.  Then I can remove that form element based on the id associated with the div.

There are many ways you can save a form, but I decided to use a button. First, I serialized the form based on the input’s name attribute.

Secondly, if the form has more than one element, you can push it into an array and submit. Otherwise, for the one form element, you can set the object and submit.

Hope you found this tutorial helpful and useful. Click here for the working demo.