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
<form id="example_form" method="post" action="index.html"> <input type="hidden" name="field_count" value="1" /> <input type="submit" /> </form>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
$('#fields_here').append('<label for="field_'+nr_of_field+'">Field '+nr_of_field+':</label><input type="text" name="field_'+nr_of_field+'" /><br />'); });Programming Language: jQuery
Now lets put all the code together and include the jQuery library.
If you catch the data then you have to make for loop, so that every cycle goes through one form field.Source code viewer
<form id="example_form" method="post" action="index.html"> <input type="hidden" name="field_count" value="1" /> <input type="submit" /> </form> <script type="text/javascript"> $('#add_field').click(function() { var nr_of_field = parseInt($('#example_form [name=field_count]').val()) + 1; $('#example_form [name=field_count]').val(nr_of_field) }); </script> Programming Language: HTML