0

I have an input and other normal button file in my site:

<input type="file" id="myid_upload_background_input" onClick="testClick();"/>

When a button is cliked, the function below is invoked by myid_templates_editor_open_file_dialog('myid_upload_background_input');

function myid_templates_editor_open_file_dialog(elemId)
{
    var elem = document.getElementById(elemId);
    if(elem && document.createEvent) {          
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, false);
        elem.dispatchEvent(evt);            
    }   
}   

function testClick(){
    alert('Click event is invoked in an input file.');
}               

After running the program by clicking the normal button, it displays the message Click event is invoked in an input file. That means the click event of the input file is successfully created, but why does the open file dialog does not open?

1 Answers1

0

Try calling .click() on input type="file" element within onclick handler of button element

document.getElementById("button").onclick = function() {
  document.getElementById("upload").click()
}

function testClick() {
  console.log("Click event is invoked in an input file.");
}
<button id="button">Click here</button>
<br/>
<br/>
<br/>
<input type="file" id="upload" onclick="testClick()" />
guest271314
  • 1
  • 15
  • 104
  • 177