Open In App

How to programmatically fire a click event for a file input element in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to programmatically fire click events on the input file element.

Approach

Whenever you want to perform a click event programmatically, at your specific condition, just use the JavaScript in-built click() function by DOM object.

Example:

document.getElementById('your_input_type_file_element_id').click();

Example 1: We want to click the input file element automatically (programmatically). When the user clicks one button which is not the ‘file upload’ button of the input type file element, we can achieve it by using the following code. 

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        programmatically fire a click event for a
          file input element in JavaScript
    </title>
</head>
 
<body>
    <input type="file" name="" id='input_file' hidden>
    <button onclick="open_file()">
        click event fire programmatically for input
        type file element
    </button>
    <script type="text/javascript">
        function open_file() {
            document.getElementById('input_file').click();
        }
    </script>
</body>
 
</html>


Output: The input file type is hidden so whenever you run this code, you easily get the select dialog for file selection. After clicking the above button, we get the file select dialog box like the one below the image.

clickkk

Output

Example 2: For example, when a user registers for your service, it registers with email, username, password, etc. Whenever a user registers successfully you give them one secret key by email or SMS. The user enters this secret in the input box on a specific page after which they are able to choose a document/ image that is needed for them.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script type="text/javascript">
        function open_file() {
            let secret_key = document
            .getElementById("secret_key").value;
            if (secret_key == "Geeksforgeeks") {
 
                // 'Geeksforgeeks' this value
                // is just an example for
                // your understanding.
                document.getElementById("input_file").click();
            }
        }
    </script>
</head>
 
<body>
    <p>Write down 'Geeksforgeeks'</p>
    <label>Enter Secret Key :</label>
    <input type="text" name="username"
    id="secret_key" oninput="open_file()" />
    <input type="file" name="" id="input_file" hidden />
</body>
 
</html>


Output: After entering the correct secret key into the input box, the file select dialog box will pop up. AJAX request is generated and it matches that user key to the original key via backend files.

yyoyoy

Output



Last Updated : 15 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads