Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file / browse dialog using javascript?

Is there any way to open the browse for files dialog box when a <a href> link is clicked using javascript? It should function like a normal browse for files button and give the names/list of files selected in response.

like image 294
Ali Avatar asked Jun 24 '11 04:06

Ali


People also ask

How to open file dialog in JavaScript?

Use the type="file" Attribute in HTML and onchange Method in JavaScript to Open File Dialog. We will create a button element in the following instance, and an onclick attribute will follow this. This will trigger a function in the JavaScript file.

How to open the selected file in JavaScript?

Simply create an input element and trigger the click. var input = document. createElement('input'); input. type = 'file'; input.

How to open file upload dialog box on button click in JavaScript?

click(function(){ $('#imgupload'). trigger('click'); }); This will open File Upload Dialog box on your button click event..


2 Answers

Here is a non-jQuery solution. Note you can't just use .click() as some browsers do not support it.

<script type="text/javascript"> function performClick(elemId) {    var elem = document.getElementById(elemId);    if(elem && document.createEvent) {       var evt = document.createEvent("MouseEvents");       evt.initEvent("click", true, false);       elem.dispatchEvent(evt);    } } </script> <a href="#" onclick="performClick('theFile');">Open file dialog</a> <input type="file" id="theFile" /> 
like image 165
Samuel Liew Avatar answered Sep 20 '22 20:09

Samuel Liew


Use this.

<script>   function openFileOption() {   document.getElementById("file1").click(); } </script>      <input type="file" id="file1" style="display:none">      <a href="#" onclick="openFileOption();return;">open File Dialog</a> 
like image 26
birendra Avatar answered Sep 22 '22 20:09

birendra