Reputation: 135
I am using jQuery and Ajax on a button, to update the value of attribute "accept" on an input file upload element, then trigger click on it. But I can only do it on Firefox. On Chrome, the trigger click event doesn't work, and on IE8, it works but cannot upload the selected file. What should I do? This is my code in handleAjaxResponseSuccess function:
$('#inputFile').attr('accept', '.jpg, .png');
$('#inputFile').click();
//in Firefox and IE8, it shows a file dialog that allows choosing file to upload. But in Chrome, the file dialog does not appear, and in IE8, the selected file cannot be uploaded
My HTML code
<button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class=""></button>
<input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >
Upvotes: 3
Views: 8182
Reputation: 242
one basic and easy way would be this:
$('#b1').on('click',function(){
alert("button #1 is clicked");
$('#b2').click();
});
$('#b2').on('click',function(){
alert("button #2 is clicked");
});
Jsfiddle: https://jsfiddle.net/vf65pzhj/1/
Upvotes: 2
Reputation: 36
For the security reasons some browsers don't allow to trigger file input directly. The action to open the dialog box MUST be called by a user interaction (a click for instance) AND the input file MUST be visible (display != none) and focused.
You can show to open dialog and after hide like this:
getAcceptedExtension = function() {
$('#inputFile').attr('accept', '.jpg, .png');
$('#inputFile').show();
$('#inputFile').focus();
$('#inputFile').click();
$('#inputFile').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class="">CLICK ME</button>
<input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >
Upvotes: 2