When a user selects a file, I want another file field to appear. It works for the first file, but if i choose a file in the second field, it doesn’t get called again. Why not?
jquery script
$(document).ready(function() {
var i = 1;
$('input:file[name$=\'uploadedFile'+(i-1)+'\']').change(function() {
var file = $(this).val();
if(file !== null && file !== "") {
$(this).after("<input type=\"file\" name=\"uploadededFile"+i+"\" />");
i++;
}
});
});
html form
<form action="PHP/file.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500000" />
<input type="file" name="uploadedFile0" />
<input type="submit" value="SUBMIT" />
</form>
When you write
$(...).change(function), you are adding the handler to the elements that are currently in the jQuery object. When you add a new<input>, it doesn;t have any event handlers.You need to call
.live, which will handle the event for all matching elements, no matter when they were created.For example:
Note that the selector is only evaluated once, so it won’t pick up changes in
i.Instead, you should use
:last.