Josef Josef - 4 months ago 8
jQuery Question

Targeting 'Open' Button On Form Upload

For aesthetic reasons I wanted to add a hidden file form to my HTML document. Ultimately, in the style of Facebook, I'd like to, upon the user clicking 'Open' after file selection, automatically post these images to another page where thumbnails are displayed and each image has associated forms which the user can edit. I'm new to web development, learning on Laravel 5.2.

I leveraged jQuery to create an event upon the user clicking the link:

$(document).ready(function () {
$("#uploadAlbumLink").on('click', function (e) {
e.preventDefault();
$("#selectImages").trigger('click');
});
})


This works fine, but I don't know how to target the 'Open' button on the file selection window, so that an additional event is triggered which activates the form submission. How would I do this? Is there another approach that is recommended?

Answer

If <input type="file"> element has name attribute set, you can use change event at <input type="file"> element to submit parent <form> element by selecting closes parent form element utilizing .closest(), .submit() when user selects files. Though allowing user to submit form the user action would probably be a clearer indication to user that uploaded files will be submitted to a server.

$("#selectImages").change(function(e) {
  if (e.target.files.length) {
    $(this).closest("form").submit()
  }
})