Trigger click on input file

I have this mark

<div id="wrapper"> <input type="file" id="file" accept="image/*" capture="camera"> <a href="#" id="capture">Submit Cleanup</a> </div> 

and jQuery as it should

 jQuery(function($){ $('#capture').on('click', function(e){ e.preventDefault(); $('#file').trigger('click'); }); }); 

The script works as expected in a PC browser, but when I try to use a mobile device, the camera does not request. I also tried using click() , but the same result.

what could be the problem?

+5
source share
3 answers

This is a safety feature. Some browsers do not allow manual clicking on an input type file. Here you can read more here and here .

Why is it not possible to programmatically run file input selection?

Most browsers prevent sending files when the input field does not receive a direct click event (or keyboard) as a precaution. Some browsers (for example, Google Chrome) simply prevent the click event, while, for example, Internet Explorer does not send files that were selected by the file input field. Firefox 4 (and later) is still the only browser with full support for invoking "click" -Events on a completely hidden (display: none) file field.

+10
source

In most browsers (

 jQuery(function($){ $('#capture').on('click', function(e){ e.preventDefault(); $('#file')[0].click(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="wrapper"> <input type="file" id="file" accept="image/*" capture="camera"> <a href="#" id="capture">Submit Cleanup</a> </div> 
+7
source

 <label> <input type="file" name="myfile" id="myfile" style="display:none"> CLICK HERE! </label> <br> <a href="javascript:document.querySelector('input#myfile').click()">OR HERE</a> 
+2
source

Source: https://habr.com/ru/post/1202744/


All Articles