26 August 2010

This tutorial is about adding form fields, more precisely how to add textboxes dynamically with JavaScript. To make the code easier I use jQuery library.

Example Form:

The hidden variable is for holding number of fields. One field is made by default. Submit button has no use in this tutorial, but its still there. Then there is div where the fields are going to appear. Button tag is for the button that generates the values, but it does not have to be button it can be anything.
Source code viewer
  1. <form id="example_form" method="post" action="index.html">
  2. <input type="hidden" name="field_count" value="1" />
  3. <label for="field_1">Field 1:</label><input type="text" name="field_1" /><br />
  4. <div id="fields_here"></div>
  5. <input type="submit" />
  6. </form>
  7. <button id="add_field">Add Field</button>
Programming Language: HTML

JavaScript for Adding Fields:

If you click item with id of add_field then you will call our function. First we get the value from the hidden field and add 1 to it. Then we append our div. We also have to increase the number of form fields.
Source code viewer
  1. $('#add_field').click(function() {
  2. var nr_of_field = parseInt($('#example_form [name=field_count]').val()) + 1;
  3. $('#fields_here').append('<label for="field_'+nr_of_field+'">Field '+nr_of_field+':</label><input type="text" name="field_'+nr_of_field+'" /><br />');
  4. $('#example_form [name=field_count]').val(nr_of_field)
  5. });
Programming Language: jQuery
Now lets put all the code together and include the jQuery library.
Source code viewer
  1. <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  2.  
  3. <form id="example_form" method="post" action="index.html">
  4. <input type="hidden" name="field_count" value="1" />
  5. <label for="field_1">Field 1:</label><input type="text" name="field_1" /><br />
  6. <div id="fields_here"></div>
  7. <input type="submit" />
  8. </form>
  9. <button id="add_field">Add Field</button>
  10.  
  11. <script type="text/javascript">
  12. $('#add_field').click(function() {
  13. var nr_of_field = parseInt($('#example_form [name=field_count]').val()) + 1;
  14. $('#fields_here').append('<label for="field_'+nr_of_field+'">Field '+nr_of_field+':</label><input type="text" name="field_'+nr_of_field+'" /><br />');
  15. $('#example_form [name=field_count]').val(nr_of_field)
  16. });
  17.  
  18. </body></html>
Programming Language: HTML
If you catch the data then you have to make for loop, so that every cycle goes through one form field.