Using jQuery to generate extensible form fields

Sometimes you may want to allow a user to add extra fields to a form on the fly. For example, an online résume form will have space for previous employment. A jobseeker fresh out of school may only have had one other job whereas a more experienced may have worked for eleven different organisations. Do you provide a form with eleven previous employment fields? Then what happens when the next applicant has had twelve jobs?

The more blank fields you put on your form the more cluttered it becomes. What you want is a way to add blank fields to the form as required.

You could use a server-side script which would generate the fields for you. However, each time you require an extra field the entire form must be submitted. An alternative is to use client-side Javascript to modify the DOM. The jQuery Javascript library makes this even easier. An example of using jQuery is demonstrated below.

<html>
<head>
<title>Jobs - Extensible Form Demonstation</title>
<script language="text/javascript" src="scripts/jquery.js"></script>
<script language="text/javascript">
$(document).ready(function(){
$("#addfield").click(function() {
strFieldTitle = 'jobhistory';
strNewField = '<tr><th>Job %</th><td><input type="text" name="job_%" id="job_%" /></td></tr>;
addField(strFieldTitle, strNewField);
});
});

function addField(strFieldTitle, strNewField) {
// We store a count of the total number of fields
strCountField = '#' + strFieldTitle + '_count';
intFields = $(strCountField).val();

// Create the new ID/Name for the form element by replacing % with the current field count
strNewField = strNewField.replace(/%/g, intFields);

// Increment the total field count and update the count field
intFields = Number(intFields) + 1;
$(strCountField).val(intFields);

// Add the new field to the bottom of the table
$("#" + strFieldName + " tr:last").after(strNewField);
}
</script>
</head>
<body>
<h1>My Jobs</h1>
<form>
<input type="hidden" name="jobhistory_count" id="jobhistory_count" value="1" />
<table id="jobhistory">
<tr>
<th>Job 1</th>
<td><input type="text" name="job_0" id="job_0" /></td>
</tr>
</table>
<p><a href="http://allrite.net/ww/#" id="addfield">[+] Add field</a></p>
</form>
</body>
</html>
Filed under: