This has been done many times before. I would recommend not writing another custom JavaScript file uploader (unless you have to for some other reason). I recommend the excellent Pulpload. I expect that it would be substantially less effort to use an existing, well-tested, proven solution over a new implementation.
Edit: That's unfortunate! However, I have built a demo that I hope will help you reach a solution. It does not perform the jQuery AJAX post()
but it does clone a form, increment the field ID numbers and then remove the old form when the "upload" is complete. For the purposes of a demo I am simulating the "upload" with a simple setTimeout()
.
Edit: Full solution with .live()
HTML:
<div>
<form>
<input type="file" id="form1_field1"/>
<input type="submit" value="Make it so" id="form1_field2"/>
</form>
</div>
JavaScript:
$('input[type="submit"]').live('click', function() {
var formClone = $('form:first-child').clone();
formClone.find('input').each(function(i) {
$(this).attr('id', $(this).attr('id').replace(/form(\d+)/, function(fullMatch, n) { return 'form'+(Number(n)+1); }));
});
var thisForm = $(this).closest('form');
$('div').append(formClone).children(':last').hide().fadeIn(1500);
// do ajax post here (faking the "upload time" with a timeout)
// but really the "hideFinishedForm" method body needs to
// go in the upload success callback
window.setTimeout(hideFinishedForm, 5000, thisForm);
return false;
});
function hideFinishedForm(formToRemove) {
$(formToRemove).remove();
// now submit the next form
$('form input[type="submit"]').trigger('click');
}
Further reading on the Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions (with an example)?