Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[jquery]How do I add file uploads dynamically?

Tags:

jquery

I want to upload multiple files, so I want to add upload fields dynamically through jquery. Now I can do it if I have a button like "add another field", and append the new upload to the form, but I want to do it a bit differently.

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

like image 804
Bluemagica Avatar asked Jan 02 '11 13:01

Bluemagica


People also ask

How can show dynamic data in jQuery?

jQuery Example to Load ListBox DynamicallyCreate UI to be appended for each user information. Download and import latest version of jQuery library files and jQuery UI files. Create custom jQuery handlers to append UI and load dynamic data into it. Trigger handlers on the mouse click event of Add User icon.

Can Ajax upload files?

html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript.

What is jQuery file upload?

jQuery HTML5 Uploader This uploader allows you to drag and drop files into an element (e.g. a <div> ) and then uploads the file (or multiple files) to a specified URL.


1 Answers

The input element has a change event that gets fired when the form field changes. So you can use the event-delegating form of on:

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

The change event is actually hooked up to the form, but only fires the handler if the event passed through an element matching the selector input[type=file]. (jQuery ensures that the change event propagates, even in environments where it doesn't by default.)

Live example: (I assume your markup would be a bit more interesting — and certainly better-looking — than shown there)

jQuery(function($) {
  $('form').on('change', 'input[type=file]', function() {
    var form = $(this).closest('form');
    form.append('<input type="file">');
  });
});
  body {
    font-family: sans-serif;
  }
  p {
    margin: 0px;
  }
<form>
  <input type='file'>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Notes:

  • If you need to support obsolete versions of jQuery without on, you can use delegate which is like the delegating form of on but with the arguments in a different order.
  • If you need to support obsolete browsers and obsolete versions of jQuery, the change event may not bubble and older jQuery didn't make it bubble for delegate (even though it did when hooked directly).

In either case, see the 2011 version of this answer (with a minor change to the JSBin links) for examples, etc.

like image 200
T.J. Crowder Avatar answered Sep 21 '22 23:09

T.J. Crowder