February 27, 2013
input file with cross-browsing simple button look
Question by Rafael El Bundas Fernandez
I have to create a button. If the user click the said button, he is prompted to choose a file to upload. After choosing the file, using Javascript or JQuery, i have to fill a form and submit it so the file can be uploaded.
The problem is that i cannot use the usual html
<input type="file" name="xml" class="custom-upload" id="custom-upload"/>
Is there anyway on how to do this? I have searched thoroughly and all the possible answears seem overly complicated so i thought i was missing a more essential solution.
Answer by Starx
You can create an image showing a image of a button instead. Then on click of that button, you can trigger the click event of the real file input.
<img id="imageButton" src="soure/to/imagebutton.jpg" />
<input type="file" id="fileImageButton" style="display: none; " />
And a little jQuery to do the trick
$("#imageButton").on('click', function() {
$("#fileImageButton").trigger('click');
});
Or, vanilla javascript
document.getElementById('imageButton').addEventListener('click', function() {
fileinput = document.getElementById('fileImageButton');
if (document.createEvent) {
var evt = document.createEvent("MouseEvents")
evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
fileinput.dispatchEvent(evt);
} else {
element.fireEvent("onclick"); //For IE
}
});