Im working on a UI form which (amongst others) allows the user to click a link to add additional file upload input fields in case he wishes to upload more than the standard 3 initial options.
Two things:
- Can’t help but think that there must be an easier way to do what i’m trying to do. Javascript was never one of my strong suits and im probably going the long way round.
- For some reason, the solution i have come up with; only allows one additional field to be added, and no more, it simply stops working! i want that another field is added each time the link is clicked; not just the once.
Below the code i’ve been working with; i’ve left in the comments so you can see what i have already been trying.
jQuery:
// add and remove addtional image upload inputs
jQuery('#add_image_upload_field').click( function( e ) {
e.preventDefault();
var newInput = '<input type="file" class="fullwidth" name="upload_attachment[]" />';
// jQuery(this).prev().append(newInput).slideDown('slow');
// jQuery('#upload_image input').filter(':last').append(newInput).slideDown('slow');
// jQuery('input[name="upload_attachment[]"]').filter(':last').append('newInput');
// jQuery('input[name="upload_attachment[]"]').append('newInput');
var addLink = '<a href="#" id="add_image_upload_field">Add another image input field</a>';
jQuery(this).parent().append(newInput);
jQuery(this).remove();
jQuery('#upload_image').append(addLink);
});
HTML:
<!-- Upload a picture -->
<fieldset name="upload_image" id="upload_image">
<label for="upload_image">Upload pictures:</label>
<input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" />
<input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" />
<input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" />
<a href="#" id="add_image_upload_field">Add another image input field</a>
<!--<input type="button" id="add_image_upload_field" value="Add another image input field" />-->
</fieldset>
i’ve seen this done on dozens of pages but just cannot get it to work; any help is appreciated.
When you replace/add a element the events attached to it will be gone. So if you are adding new images and want to attach a event handler you need to delegate to a element already present when the page loaded. Like:
Demo here