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?
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.
html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript.
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.
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:
on
, you can use delegate
which is like the delegating form of on
but with the arguments in a different order.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With