A few years ago I wrote a post on how to add more fields without reloading the page using javascript, but that method was kind of clunky and involved a hack to get it to work with the DOM. The following is a much easier way, and (as far as I've tested) compatible with all major browsers.
First off, download the latest version of jquery and include it on your page, or just include the following line if you trust google to host your jquery file:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Here's a sample html form – adjust according to your needs:
<form action='mypage' method='post' accept-charset='utf-8'> <ul id='myfields'> <li> <input type='text' name='mytextfield[]' /> </li> </ul> <div id='addmorelink'> <a href='javascript:addField()'>add more</a> </div> </form>What's important is the ul with the 'myfields' id, and the link that calls the 'addField()' js function.
The javascript code is very short and straightforward – basically copy your list item with the form field code into the content of the 'newContent' variable, make sure you escape quotes if you enclose the string with the same quotes as in your form field, and then use the jquery 'append' function to add the next field to your form, et voila, that's it!
<script type="text/javascript"> function addField(){ var newContent = "<li><input type='text' name='mytextfield[]'/></li>"; $("#myfields").append(newContent); } </script>I haven't mentioned one last piece that's going to come in handy on the server side where you're going to process the fields. You probably noticed the [] brackets behind the field name in the form – that turns the field into an array. On the server side, depending on what programming language you use, you just need to handle your post variable as an array – so to retrieve each value you'll need to loop through the array. Assuming you're programming in php and you're not using a framework that handles post variables differently:
<?php if(isset($_POST['mytextfield'] && is_array($_POST['mytextfield']){ foreach($_POST['mytextfield'] as $value){ // do something with each $value } } ?>