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.
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 thePOSTmethod.
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.
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!
Currently working on the tabular form (excel type), can you site any reference how to do this, like adding rows dynamically?
Hi John,
I would recommend search for some nice JQuery plugins for this. Here is one which I found but there are several others that might fit the bill:
http://warpech.github.com/jquery-handsontable/
Allen
Hi, It’s perfect sample and help.I want to thank you.
If its possible can you give example how to get textarea data with vbscript asp? ” + FPL + “” Best regards.
Sorry, I’m very familiar with VBScript. If you are working with ASP.NET, you should be able to use the JavaScript and HTML code as is.
Allen
Thank you Allen for this perfect tutorial.
You’re welcome =) I’m glad it helped out.
Allen
Great help. But I see it can not be used to add a dropdown menu itself?
I have two drop down menus int a form that provide options for two different kinds of specifications of a product item. I want to be able to have an “Add Item” option for users who want more than one product, but each with different specifications. So I basically need the “Add Item” button to generate two or more extra dropdown menus with the original data in them, for a new item. How can I do this?
Hi Nita,
You can have the extra dropdown menus “hidden” with the display attribute set to none. If a user pushes the “Add Item” button, you can simply change the CSS of the dropdown menus via JavaScript to make the visible.
Allen
Thanks Bro………..
What’s the licensing for your code?
None! Feel free to use it however you like :)
I’m very grateful for this clear and coherent explanation!
-lbfromla
nice job bro, I’ve been searching for this before now i found it. thanks a lot
Would you happen to know how to send the form input info with ASP?
I am currently learning ASP.NET MVC3. If that is what you are using, you can simply have a submit button with the form action set to the “/controller/action” (assuming you did not change the default routing). There is a bit more to this though like having your action use FormCollection. Read here for more details:
http://stackoverflow.com/questions/5088450/simple-mvc3-question-how-to-retreive-form-values-from-httppost-dictionary-or
Allen
Hi. Nice work.
Thanks, this puts me on the right track for another project that I’m planning. Can anyone show a simple example of how to display another textfield based on a checkbox being selected? An example would be to allow a visitor to add their cell phone number. If the checkbox is not clicked the Cell Phone field is not displayed on the form, if it is, the field is displayed. I’m actually planning to use this functinality where a visitor has multiple addresses but only the primary would be displayed if they only had one address.
Thanks for any examples that can be provided.
review hiding div tags, and write the fields, but hide the div tags if checked=’checked’