0

I'm trying to programmatically open a file input from javascript and it's not working in Safari (13.0.5). This file input is not hidden or anything. I've tried all these different ways so far:

<input type="file" id="markupImport"></input>

$('#markupImport').click()
$('#markupImport').trigger('click')

document.getElementById('markupImport').click()
document.getElementById('markupImport').trigger('click')

event = document.createEvent('MouseEvents')
event.initEvent('click', true, false)
$('#markupImport')[0].dispatchEvent(event)
document.getElementById('markupImport').dispatchEvent(event)

event = document.createEvent('MouseEvents')
event.initMouseEvent('click', true, true, window)
$('#markupImport')[0].dispatchEvent(event)
document.getElementById('markupImport').dispatchEvent(event)

document.getElementById('markupImport').dispatchEvent(new Event('click'))

I've looked at In JavaScript can I make a "click" event fire programmatically for a file input element?, calling click event of input doesn't work in Safari, Unable to click input type="file" in windows safari browser, Programmatically trigger "select file" dialog box, and all the others I can find already.

I'm trying to do this from a select onchange handler when a certain option is selected:

<select id="markupImport">
  <option value="Import">Import</option>
  <option value="Export">Export</option>
</select>
<input type="file" id="markupImport"></input>

$(function() {
  $('#markupImport').change(function(event) {
    if (event.target.value == 'Import') {
      $('input[name="markupImport"]').click();
    }
  });
});

I'm wondering if it's not even possible to do this in Safari anymore.

kmanzana
  • 1,138
  • 1
  • 13
  • 23
  • So you're trying to programmatically trigger a click event to open the file dialog? – mwilson Feb 07 '20 at 22:50
  • Correct. I'm using a select dropdown to call some JS to do this – kmanzana Feb 08 '20 at 03:18
  • Does this answer your question? [Programmatically trigger "select file" dialog box](https://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box) – mwilson Feb 08 '20 at 05:31
  • @mwilson, that answer is the same as `$('#markupImport').click()` above which I said I already tried and doesn't work in Safari – kmanzana Feb 10 '20 at 19:03
  • 1
    It seems like this might have to do with Safari not allowing a select changed event to be used to trigger opening the file upload. If I have a button instead with an `onclick` handler that clicks the file input, it does open – kmanzana Feb 10 '20 at 19:49
  • @kmanzana how did you manage to solve your issue? document.getElementById("uploadGalleryPhoto").click() not working for me in ios? – sinan Jan 02 '23 at 06:10
  • @sinan, sorry I missed this earlier. I don't recall what I did, but I might have just used a button instead of trying to be fancy about it as Safari isn't very lenient – kmanzana Apr 26 '23 at 18:35

0 Answers0