How to open a file dialog box when an a tag is clicked with JavaScript?

Sometimes, we want to open a file dialog box when an a tag is clicked with JavaScript.

In this article, we’ll look at how to open a file dialog box when an a tag is clicked with JavaScript.

How to open a file dialog box when an a tag is clicked with JavaScript?

To open a file dialog box when an a tag is clicked with JavaScript, we can call e.preventDefault on the a element’s click handler.

And then we call input.click to open the file dialog.

For instance, we write:

<input type="file" multiple style='display: none' />
<a>Upload</a>

to add a file input and an a element.

Then we write:

const a = document.querySelector('a')
const input = document.querySelector('input')
a.onclick = (e) => {
  e.preventDefault()
  input.click()
}

to select the a and input elements.

And then we set a.onclick to a function that calls e.preventDefault to stop the default behavior for links.

And then we call input.click to open the file dialog.

Conclusion

To open a file dialog box when an a tag is clicked with JavaScript, we can call e.preventDefault on the a element’s click handler.

And then we call input.click to open the file dialog.