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 JavaScript in-built click() function by DOM object. For 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 > < script type = "text/javascript" > function open_file() { document.getElementById('input_file').click(); } </ script > < body > < input type = "file" name = "" id = 'input_file' hidden> < button onclick = "open_file()" > click event fire programmatically for input type file element </ button > </ 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.
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 document/ image whatever 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 == "Geeksforneveropen") { // 'Geeksforneveropen' this value is just an example for // your understanding. document.getElementById("input_file").click(); } } </ script > </ head > < body > < p >Write down 'Geeksforneveropen'</ 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.