Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input event on file type not firing in Safari browser

Tags:

jquery

safari

I am uploading a file using AJAX and jQuery. It is working well in Chrome and Firefox but the problem I am getting is in Safari. I tried to debug this but the debugger did not stop when I upload the file.

<input type="file" class="file_input" name="myfile"/>
$(document).on('input', '.file_input', function() {
  var that = $(this);
  var formData = new FormData();
  formData.append("userfile", this.files[0]);
  showLoader();

  $.ajax({
    cache: false,
    headers: {
      'X-CSRF-Token': _token
    },
    url: base_url + "controller/action",
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    success: function(data) {
      that.closest('tr').find('.document').empty();
      hideLoader();
    }
  });
});
like image 508
fat potato Avatar asked Oct 11 '19 12:10

fat potato


2 Answers

Safari does not support the input event on file input elements:

(Safari and some other browsers) don't fire an input event when (un)checking a checkbox or radio button, or when changing the selected file(s) of an . See Chrome bug, WebKit bug, and Firefox bug

https://caniuse.com/#feat=input-event

To fix this you can use the more widely supported change event instead:

$(document).on('change', '.file_input', function() {
  // your code...
});

- 2020 Update -

This issue in Safari was fixed in version 13.1, released in March 2020. To be clear, any version of Safari since then now supports the input event on a file input.

If you have a requirement to support legacy versions of Safari, then you will still need to use the change event, as outlined in my original answer above.

like image 95
Rory McCrossan Avatar answered Oct 13 '22 00:10

Rory McCrossan


Try to set accept attribute on your input. So the best course of action here is maybe to add both MIMEs and extensions on inputs.

<input
    type="file"
    id="attachments" 
    accept="application/msword,image/gif,image/jpeg,application/pdf,image/png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/zip,.doc,.gif,.jpeg,.jpg,.pdf,.png,.xls,.xlsx,.zip" 
    name="myfile"
    class="file_input"
>
like image 41
Daniel Smith Avatar answered Oct 12 '22 23:10

Daniel Smith