Adding Form Fields Dynamically with jQuery

Note: There is a newer post that repeats the same functionality of this example but makes use of Knockout.js - Adding Form Fields Dynamically with Knockout.js

Sometimes, for example with a content management system, the user needs the ability to add fields dynamically to a HTML form. As jQuery is the King of DOM then this is an easy task for it to implement.

In this example, we'll use jQuery to create a new node that contains the new form element (in this case a simple textfield) and then add it to DOM.

To make it even more interactive we'll give the user the ability to remove form fields so that they can customise the form to their requirements.

View The Demo

The HTML is just the shell of a form.

<form method="post">
<p>
<span id="addVar">Add Variable</span>
</p>
<p>
<input type="submit" value="Check">
</p>

</form>

When clicking the HTML marked up a as <span id="addVar">Add Variable</span> we want the following HTML added to create a new paragraph that contains a label and textfield.

<p>
<label for="var2">Variable 2: </label>
<input type="text" name="var2" id="var2"><span class="removeVar">Remove Variable</span>
</p>

We'll do this by creating a variable containing the HTML and adding it to the DOM. The HTML contains the seeds of its own destruction. The removeVar class can be used to remove the element.

In this example there is also a block of similar logic to initially add three textfields to the form - although this is not required.

Time for that jQuery magic.

//create three initial fields
var startingNo = 3;
var $node = "";
for(varCount=0;varCount<=startingNo;varCount++){
    var displayCount = varCount+1;
    $node += '<p><label for="var'+displayCount+'">Variable '+displayCount+': </label><input type="text" name="var'+displayCount+'" id="var'+displayCount+'"><span class="removeVar">Remove Variable</span></p>';
}
//add them to the DOM
$('form').prepend($node);
//remove a textfield
$('form').on('click', '.removeVar', function(){
   $(this).parent().remove();

});
//add a new node
$('#addVar').on('click', function(){
varCount++;
$node = '<p><label for="var'+varCount+'">Variable '+varCount+': </label><input type="text" name="var'+varCount+'" id="var'+varCount+'"><span class="removeVar">Remove Variable</span></p>';
$(this).parent().before($node);
});

The jQuery prepend() method is used to add the initial fields and the jQuery before() method adds a new field when the user clicks addVar in the HTML.