Dynamically Add or Remove Fields using jQuery or JavaScript

Here is a Simple example, how you can have the “Add More” feature in a Form.
I have used Array splice() Method here in this example. The splice() method adds/removes items to/from an array, and returns the removed item(s).
You This Code Snippet uses jQuery, who creates all the magic…!! ;). For CDN Link, click here .
Array .splice()
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
Syntax
array.splice(index, no of items, item1, ….., itemX);
Parameters
index :: It is a required Parameter of type integer. The integer specifies the position in the array at which the items will be added or removed.
no of items :: It is an optional Parameter of type integer. It specifies how many items to be removed. If you don’t want to remove any items, set it to 0.
item1, …, itemX :: It is an optional Parameter. This sets the item(s) to be added to the array. This can be a single item or multiple items.
Example
Note:: The following examples of .splice() are written in pure JS, no libraries used. But you can use jQuery. I have used jQuery in the final code.
- To add a single item to the array:
2. To add multiple items to the array:
3. To remove items from the array:
4. To remove existing and add new item in the array:
By now we have covered how .splice() works. So with this I have written the “Add More” Feature. Go through and try out the fiddle to have a complete understanding.
Feel free to give your Feedback and suggest if any changes required.
If this helped, applauds welcomed. 🙂 Cheers!!
