How to dynamically add form elements via JavaScript



Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.

Demo
Entry 1



Here is the plain HTML for the form:

<script src="/wp-includes/js/addInput.js" language="Javascript" type="text/javascript"></script>
<form method="POST">
     <div id="dynamicInput">
          Entry 1<br><input type="text" name="myInputs[]">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>

When the user clicks on the Add another text input button, the addInput JavaScript function is executed and given the dynamicInput argument which is the name of the div that contains all our text inputs. Here is what our JavaScript function looks like:

var counter = 1;
var limit = 3;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

There are a couple of global variables:

  • counter – Tracks the number inputs being added.
  • limit – The maximum number inputs allowed for the user to add. In this case, we are limiting the user to a maximum of 3 input texts that they can submit with the form.

The addInput JavaScript function expects a parameter, which in this case is the id of the div, to add the dynamic text inputs. Once executed, the function will first check to see if the maximum number of input texts have already been used. If so, an alert will be given stating that the limit has been reached.

If the limit has not been reached, then the else block of the code is executed. A new div element is created and the inner HTML is set with 2 things:

  • Entry # – The global variable, counter, keeps track of the current number of text inputs that are in the form.
  • The input text element – The name of these text inputs,myInputs[], is followed by square brackets to indicate that it is an array. This will be more important later on when the form is submitted using the POST method.

If the form gets submitted to a PHP file, you can easily access each input value for your myInputs array. Here is the PHP code for doing just that:

$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput) {
     echo $eachInput . "<br>";
}

This is just a sample code to echo all the text input values that were sent from the form. An array variable, $myInputsPHP, is initialized with the myInputs from the form. Then, the foreach loop will go through each value and print them out.

Here is another version of this script that adds different types of inputs such as text fields, radio buttons, checkboxes, and textareas. To simplify things, the limit functionality has been removed.

Demo
Let’s start adding some inputs of different types.


Here is the plain JavaScript code for the addAllInputs function. It accepts 2 arguments:

  • div id – This is the div id where all the dynamic inputs will be added to.
  • input type – This is the type of input that we want to add.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var counterText = 0;
var counterRadioButton = 0;
var counterCheckBox = 0;
var counterTextArea = 0;
function addAllInputs(divName, inputType){
     var newdiv = document.createElement('div');
     switch(inputType) {
          case 'text':
               newdiv.innerHTML = "Entry " + (counterText + 1) + " <br><input type='text' name='myInputs[]'>";
               counterText++;
               break;
          case 'radio':
               newdiv.innerHTML = "Entry " + (counterRadioButton + 1) + " <br><input type='radio' name='myRadioButtons[]'>";
               counterRadioButton++;
               break;
          case 'checkbox':
               newdiv.innerHTML = "Entry " + (counterCheckBox + 1) + " <br><input type='checkbox' name='myCheckBoxes[]'>";
               counterCheckBox++;
               break;
          case 'textarea':
	       newdiv.innerHTML = "Entry " + (counterTextArea + 1) + " <br><textarea name='myTextAreas[]'>type here...</textarea>";
               counterTextArea++;
               break;
          }
     document.getElementById(divName).appendChild(newdiv);
}

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!