I'm building an employment application form that's dynamic. I want a field that asks for the number of prior employers, whe开发者_如何学Cn they enter an number say 3 it will duplicate a div with these fields 3 times, subsequently updating each name and value field with a number at the end ex: field1, field2, field3.
Fields I need: Employer Name, Title, Supervisor, Address, State, Zip, Phone
Does that make sense? How do I do this? I have no code expect a html input field.
I'd do it with a for loop and jquery's append() function.
$("#employee_fields_generate").click(function ()
{
$("#employee_fields").html("");
var number_employees = $("input[name='number_employees']").val();
for (i=0; i<=number_employees; i++)
{
$("#employee_fields").append('<div id="employee'+i+'"> //your field inputs go here </div>');
}
});
<form id="employees_form">
<label for="number_employees">Number of Employees:</label><input type="text" name="number_employees" />
<button id="employee_fields_generate">Generate Fields!</button>
<div id="employee_fields">
</div>
</form>
You could have something like this if you want to allow them to adjust the number without losing their first entries.
$('input[name=prior_employers]').keyup(function(){
var how_many = parseInt($(this).val());
if(how_many < 1 || isNaN(how_many)) { $('.employer-group').remove(); return; }
$('.employer-group:gt('+how_many+')').remove();
var employers = $('.employer-group');
if (employers.length < how_many) {
var container = $('#employer-container');
for(i=employers.length; i<=how_many; i++) {
container.append('<div class="employer-group"><input type="text" name="employer['+i+'][name]"/></div>');
}
}
});
精彩评论