[jquery] How to add dynamic file downloads?

I want to upload multiple files, so I want to dynamically add upload fields via jquery. Now I can do this if I have a button like โ€œadd another fieldโ€ and add a new upload to the form, but I want to do it a little differently.

Initially, the form should have one input field after the user selects a file to upload. I want to immediately add another download field. Any ideas on how to do this?

+7
source share
2 answers

The input element has a change event that fires when the form field changes. So:

 $('selector_for_your_form').delegate('input[type=file]', 'change', function() { var form = $(this).closest('form'); form.append(/* ... markup for the new field ... */); }); 

Uses delegate , which means you donโ€™t need to explicitly bind the event to a new element.

Real-time example (I assume your markup will be a little more interesting - and certainly looks better - than shown there)

Update . Unfortunately, change does not start immediately in some browsers (it waits until the user distracts the focus from the field in IE7, for example). jQuery handles this weirdness for you if you are attaching an event directly but not using delegate . So here is an alternative:

 $('selector_for_your_form input[type=file]').change(fileChangeHandler); function fileChangeHandler() { var form = $(this).closest('form'); $('<input type="file">').change(fileChangeHandler).appendTo(form); } 

If your markup is more complex than input itself (and I assume it is), you need to be sure that you are connecting change to the right element.

Living example

+11
source

You can try something like this.

 <input type="file" name="file" onChange="if ($(this).val() != '' {addNewfileInput();}"> 
0
source

All Articles