Categories
JavaScript Answers

How to programmatically trigger select file dialog box with JavaScript?

Spread the love

You can programmatically trigger the file dialog box in JavaScript by simulating a click event on a hidden <input type="file"> element.

To do this, we:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trigger File Dialog</title>
</head>
<body>
    <!-- Hidden input element -->
    <input type="file" id="fileInput" style="display: none;">

    <!-- Button to trigger the file dialog -->
    <button onclick="openFileDialog()">Open File Dialog</button>

    <script>
        // Function to open the file dialog
        function openFileDialog() {
            // Trigger click event on the hidden file input element
            document.getElementById('fileInput').click();
        }
    </script>
</body>
</html>

In this example, we have a hidden <input type="file"> element with the ID fileInput.

We also have a button labeled “Open File Dialog.”

When the button is clicked, it triggers the openFileDialog() function.

Inside the openFileDialog() function, we use document.getElementById() to get a reference to the hidden file input element, and then we simulate a click event on it by calling the click() method.

This approach allows you to programmatically open the file dialog box without the user having to manually click on an <input type="file"> element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *