HTML how to remove text in FileUpload field? - javascript

When I have a file upload field,
<form action="" method="post" enctype="multipart/form-data">
<input id="image" type="file" name="image">
</form>
http://jsfiddle.net/jakeaustin5574/6DzgU/
It automatically creates a text "No file chosen" and a "Browse" button.
I want to change or remove this "No file chosen" text.
Is there anyway to achieve this in css or Javascript?
Thanks

You can apply css rules like...
input[type=file]{
color:transparent;
}

First of all. You have to hide your input:
input#image{position:fixed;top:-100px;}
Secondly, you have to create alternative button with your skin:
<form action="" method="post" enctype="multipart/form-data">
<input id="image" type="file" name="image">
<button id="image_alt">Select image</button>
</form>
and the last step is to create a javascript script which link alternative button with original one:
document.getElementById('image_alt').addEventListener('click',function(){
document.getElementById('image').click();
});
Example Fiddle

You can set the value of the image input to "" using jQuery to remove the selected file:
$("#image").val("")
See this fiddle:
http://jsfiddle.net/nfvR9/1/
NOTE: This is dependent on browser used. It's works in FF 22 and Chrome 29.

I am sure you cannot change the default labels on buttons, they are hard-coded in browsers (each browser rendering the buttons captions its own way). check this styling article

HTML:
<div class="inputWrapper">
<input class="fileInput" type="file" name="file1"/>
</div>
CSS:
.inputWrapper {
height: 32px;
width: 64px;
overflow: hidden;
position: relative;
cursor: pointer;
/*Using a background color, but you can use a background image to represent a button*/
background-color: #DDF;
}
.fileInput {
cursor: pointer;
height: 100%;
position:absolute;
top: 0;
right: 0;
z-index: 99;
/*This makes the button huge. If you want a bigger button, increase the font size*/
font-size:50px;
/*Opacity settings for all browsers*/
opacity: 0;
-moz-opacity: 0;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}
take a look of this fiddle:
its working for your needs.
FIDDLE - DEMO
this demo its a reference of this:
stackoverflow question LINK
From the autor:ampersandre

<div style="position:relative;display:inline-block;left:-4px;bottom:-6px;width:16px;height: 24px;overflow:hidden;">
<img src="http://maps.google.com/mapfiles/ms/micons/blue-dot.png" alt="" title="Add Attachment" style="height:24px;width:24px; position: relative;top: 1px; left: -3px;"/>
<input type="file" id="fileupload" name="upload" style=" opacity: 0;font-size: 50px;width:16px; filter:alpha(opacity: 0); position: relative; top: -25px; left: -1px" />
</div>
JQuery:
function getFileName() {
var varfile = $('#fileupload').val().replace(/.*(\/|\\)/, '');
$("#filename").text(varfile);
}
$("#fileupload").on('change', function() {
getFileName();
});
Demo:
http://jsfiddle.net/m44fp2yd/

$(function () {
$('input[type="file"]').change(function () {
if ($(this).val() != "") {
$(this).css('color', '#333');
}else{
$(this).css('color', 'transparent');
}
});
})
input[type="file"]{
color: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="app_cvupload" class="fullwidth input rqd">

The No file chosen text is entirely dependent on the browsers rendering engine - I assume you use Chrome. If Firefox you'll see No file selected and in IE you'll get a greyed out textbox with no value at all. This cannot be changed.
The alternative is to use a plugin (such as this) which gives you complete control over the styling of the file control.

It's up to the browser to render the file upload box. Each one does this in your own way. For example, in my chrome I can see the No file chosen text. Someone using Firefox might see something else entirely. There is no direct way to control this rendering process.
However, there are some hacks which can be used. For details, check out this link.

this text show by browser different browser show different message
chrome show=no file choosen
mozilla show=no file selected
and same as ie

Related

Open browser-standard colorpicker with javascript without type=color

Does anyone knows a javascript only way to open the browser-standard colorpicker, without using a html field? so i want a javascript what does exactly the same a a click on the html input color field.
Bart
You are going to have to use the input field, you can just hide it off the page. Issue here is the fact that the color dialog requires a click in browsers in order to open up the color dialog. It will not work if you just call click()
document.getElementById("xxx").addEventListener("click", function() {
document.getElementById("c").focus();
document.getElementById("c").value = "#FFCC00";
document.getElementById("c").click();
});
.hidden {
position: absolute;
left: -10000px;
top: auto;
width: 1px;
height: 1px;
overflow: hidden;
}
<input type="color" id="c" tabindex=-1 class="hidden">
<input type="button" id="xxx" value="Click Me!">
Here's a good old "hover-hack" solution that works even in MS Edge:
<input type="color" style='opacity:0;width:100px;position:absolute;'/>
<button>clickme</button>
then bind onchange to the colro element
https://jsfiddle.net/Lnzm0sry/2/

Opening a javascript dialog box to store to the complete file location into a var

I need your help.
I would like to design a javascript function, such that when I call it, it will open up a dialog box asking me to navigate to the selected file, once I click on the "open" button, it will then save the file's path into a var.
How do you do this? I would NOT like to the input type="file" method, as I dont require that particular input to be on my page.
ie:
function getlocation() {
var x = popup the open file dialog box and let the user select a file
}
The only way to allow the user to select a file is to use an <input type="file" />1. You don't have to have this element visible, just on the page.
When a user selects a file, all you can get from it is its name. You cannot get its path. Also, note that file upload elements are asynchronous. You need to use the onchange event (callback) to get the name.
You can hide the upload element using display: none, and then just have another JavaScript function programmatically trigger it. (NOTE: This method doesn't work in Opera, and possibly other browsers. It was tested in Chrome, Firefox, and IE 8/9)
<style>
#getFile{
display: none;
}
</style>
<input type="file" id="getFile" />
<button id="openFile" type="button">Click Me</button>
<script>
var uploadElement = document.getElementById('getFile'),
uploadTrigger = document.getElementById('openFile'),
openFileUpload = function(){
uploadElement.click();
},
alertValue = function () {
alert(uploadElement.value);
};
if (window.addEventListener) {
uploadTrigger.addEventListener('click', openFileUpload);
uploadElement.addEventListener('change', alertValue);
} else {
uploadTrigger.attachEvent('onclick', openFileUpload);
uploadElement.attachEvent('onchange', alertValue);
}
</script>
DEMO: http://jsfiddle.net/rJA7n/3/show (Edit it at: http://jsfiddle.net/rJA7n/3/)
Another method that should work in most browsers (including Opera) is to make the file upload element "invisible" and put an element on top of it. So, when you click on what you think is a button, you're really clicking on the upload element. AJAX uploaders (like http://fineuploader.com/) use this method to allow you to "style" upload buttons.
<style>
#getFile{
width: 100px;
opacity: 0;
filter: alpha(opacity = 0);
}
#openFile{
display: inline;
margin-left: -100px;
background-color: red;
height: 30px;
width: 100px;
padding: 10px;
color: white;
text-align: center;
}
</style>
<input type="file" id="getFile" />
<div id="openFile">Click Me</div>
<script>
var uploadElement = document.getElementById('getFile'),
alertValue = function(){
alert(uploadElement.value);
};
if(window.addEventListener){
uploadElement.addEventListener('change', alertValue);
}
else{
uploadElement.attachEvent('onchange', alertValue);
}
</script>
DEMO: http://jsfiddle.net/cKGft/4/show/ (Edit it at: http://jsfiddle.net/cKGft/4/)
1 Well, you can use drag and drop if you want to be really fancy. I made a quick demo of that here: http://jsfiddle.net/S6BY8/2/show (edit it at: http://jsfiddle.net/S6BY8/2/)

How to style "input file" with CSS3 / Javascript? [duplicate]

This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 7 years ago.
I would like to style <input type="file" /> using CSS3.
Alternatively, I would like user to press on a div (that I will style) and this will open the Browse window.
Is that possible to do that using HTML, CSS3, and Javascript / jQuery only ?
I have this rough example that you might want to get some idea...
html​
<div id="file">Chose file</div>
<input type="file" name="file" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
CSS
#file {
display:none;
}​
jQuery
var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function(){
$this = $(this);
$('#file').text($this.val());
})
$('#file').click(function(){
fileInput.click();
}).show();
demo
​​​​​​​​​​​​​​
After checking Reigels idea, and this one, I wrote this simple solution to the common problem of styling a type="file" input field (tested it on Firefox, Safari and Chrome).
<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').innerHTML = this.value;">
</div>
Then you can of course style the "file" div as you want.
And if you want to use a type="text" input instead of a div, simply change innerHTML for value:
<div style="position:relative;">
<input type="text" id="file" style="position:absolute;" placeholder="Click here to select a file">
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').value = this.value;">
</div>
Here is my original answer using jQuery:
<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="$('#file').text($(this).val());">
</div>
I made a custom style for this as well. Check it out
JS Fiddle Demo - Custom Input type="file"
HTML
<input type="file" id="test">
<div class="button-group">
Browse
Save
Clear
</div>
<input type="text" id="testfile"></input>
CSS
body {
padding:100px;
}
input[type="file"] {
position:absolute;
display:none;
}
#testfile {
height: 26px;
text-decoration: none;
background-color: #eee;
border:1px solid #ccc;
border-radius:3px;
float:left;
margin-right:5px;
overflow:hidden;
text-overflow:ellipsis;
color:#aaa;
text-indent:5px;
}
#actionbtnBrowse, #actionbtnSave {
margin:0 !important;
width:60px;
}
JQuery
$("#browse").click(function () {
$("#test").click();
})
$("#save").click(function () {
alert('Run a save function');
})
$("#clear").click(function () {
$('#testfile').val('');
})
$('#test').change(function () {
$('#testfile').val($(this).val());
})
Also add to external resources tab:
https://github.com/necolas/css3-github-buttons/blob/master/gh-buttons.css
Here is how to do it using HTML, CSS and Javascript (without any frameworks):
The idea is to have the <input type='file'> button hidden and use a dummy <div> that you style as a file upload button. On click of this <div>, we call the hidden <input type='file'>.
Demo:
// comments inline
document.getElementById("customButton").addEventListener("click", function(){
document.getElementById("fileUpload").click(); // trigger the click of actual file upload button
});
document.getElementById("fileUpload").addEventListener("change", function(){
var fullPath = document.getElementById('fileUpload').value;
var fileName = fullPath.split(/(\\|\/)/g).pop(); // fetch the file name
document.getElementById("fileName").innerHTML = fileName; // display the file name
}, false);
body{
font-family: Arial;
}
#fileUpload{
display: none; /* do not display the actual file upload button */
}
#customButton{ /* style the dummy upload button */
background: yellow;
border: 1px solid red;
border-radius: 5px;
padding: 5px;
display: inline-block;
cursor: pointer;
color: red;
}
<input type="file" id="fileUpload"> <!-- actual file upload button -->
<div id="customButton">Browse</div> <!-- dummy file upload button which can be used for styling ;) -->
<span id="fileName"></span> <!-- the file name of the selected file will be shown here -->
The fake div is not needed! No Js no extra html. Using only css is possible.
The best way is using the pseudo element :after or :before as an element overt the de input. Then style that pseudo element as you wish. I recomend you to do as a general style for all input files as follows:
input[type="file"]:before {
content: 'Browse';
background: #FFF;
width: 100%;
height: 35px;
display: block;
text-align: left;
position: relative;
margin: 0;
margin: 0 5px;
left: -6px;
border: 1px solid #E0E0E0;
top: -1px;
line-height: 35px;
color: #B6B6B6;
padding-left: 5px;
display: block;
}
--> DEMO
In addition of Reigel,
here is more simpler implementation. You can use this solution on multiple file input fields, too. Hope this helps some people ;-)
HTML (single input)
<input type="file" name="file" />
HTML (multiple input)
<!-- div is important to separate correctly or work with jQuery's .closest() -->
<div>
<input type="file" name="file[]" />
</div>
<div>
<input type="file" name="file[]" />
</div>
<div>
<input type="file" name="file[]" />
</div>
JavaScript
// make all input fields with type 'file' invisible
$(':file').css({
'visibility': 'hidden',
'display': 'none'
});
// add a textbox after *each* file input
$(':file').after('<input type="text" readonly="readonly" value="" class="fileChooserText" /> <input type="button" value="Choose file ..." class="fileChooserButton" />');
// add *click* event to *each* pseudo file button
// to link the click to the *closest* original file input
$('.fileChooserButton').click(function() {
$(this).parent().find(':file').click();
}).show();
// add *change* event to *each* file input
// to copy the name of the file in the read-only text input field
$(':file').change(function() {
$(this).parent().find('.fileChooserText').val($(this).val());
});
Here's an example that I'm using that utilizes jQuery, I've tested against Firefox 11, and Chrome 18, as well as IE9. So its pretty compatible with browsers in my book, though i only work with those three.
HTML
Here's a basic "Customizable" HTML structure.
<span>
File to Upload<br />
<label class="smallInput" style="float:left;">
<input type="file" name="file" class="smallInput" />
</label>
<input type="button" class="upload" value="Upload" style="float:left;margin-top:6px;margin-left:10px;" />
</span>
CSS
Here's a sample of my CSS
label.smallInput {
background:url(images/bg_s_input.gif) no-repeat;
width:168px;
}
JavaScript
This is the heavy lifter.
/* File upload magic form?? */
$("input.smallInput[type=file]").each(function(i){
var id = "__d_file_upload_"+i;
var d_wrap = $('<div/>').attr('id',id).css({'position':'relative','cursor':'text'});
$(this).wrap(d_wrap).bind('change blur focus keyup click',function(){
$("#"+id+" input[type=text]").val($(this).val());
}).css({'opacity':0,'zIndex':9999,'position':'absolute'}).removeClass('smallInput');
obj = $(this);
$("#"+id).append($("<input/>").addClass('smallInput').attr('type','text').css({'zIndex':9998,'position':'absolute'}).bind('click',function(e){obj.trigger('click');$(this).blur();}));
obj.closest('span').children('input.upload[type=button]').bind('click',function(e){
obj.trigger('click');
$(this).blur();
});
});
/* ************************ */
Explanation
The HTML is pretty straight forward, just a simple element, i include the button so it can be named independently from the rest, sure this could be included in the JavaScript, but simply put, I'm a bit on the lazy side. The code searches for all inputs with a class of smallInput that have the type of file this allows you to define default HTML and fallback form structure in case a browser decides to be a pain.
This method only uses JavaScript to ensure delivery, it does not alter any browser behaviors in regards to the file input.
You can modify the HTML and JavaScript to make it very robust, this code suffices my current project so i doubt I'll be making any changes to it.
Caveats
Different browsers treat the value of the file input differently, which in chrome results in c:\fakeroot\ on windows machines.
Uses anonymous functions, (for lack of a better word) which means if you have too many file inputs you can cause the browser to behave slowly on processing.
Ran into the same issue today, but it seems there's an easy way to have your own styles - hide the input, and style the associated label:
<div class="upload">
<label for="my-input"> Upload stuff </label>
<input type="file" id="my-input" name="files[]" />
</div>
CSS:
.upload input{
display: none;
}
.upload label{
background: DarkSlateBlue;
color: white;
padding: 5px 10px;
}
Works in latest Chrome, Firefox and IE 10. Didn't test others
While Reigel's answer conveys the idea, it doesn't really have any style attached to it. I came across this problem recently and despite the plethora of answers on Stack Overflow, none really seemed to fit the bill. In the end, I ended up customizing this so as to have a simple and an elegant solution.
I have also tested this on Firefox, IE (11, 10 & 9), Chrome and Opera, iPad and a few android devices.
Here's the JSFiddle link -> http://jsfiddle.net/umhva747/
$('input[type=file]').change(function(e) {
$in = $(this);
$in.next().html($in.val());
});
$('.uploadButton').click(function() {
var fileName = $("#fileUpload").val();
if (fileName) {
alert(fileName + " can be uploaded.");
}
else {
alert("Please select a file to upload");
}
});
body {
background-color:Black;
}
div.upload {
background-color:#fff;
border: 1px solid #ddd;
border-radius:5px;
display:inline-block;
height: 30px;
padding:3px 40px 3px 3px;
position:relative;
width: auto;
}
div.upload:hover {
opacity:0.95;
}
div.upload input[type="file"] {
display: input-block;
width: 100%;
height: 30px;
opacity: 0;
cursor:pointer;
position:absolute;
left:0;
}
.uploadButton {
background-color: #425F9C;
border: none;
border-radius: 3px;
color: #FFF;
cursor:pointer;
display: inline-block;
height: 30px;
margin-right:15px;
width: auto;
padding:0 20px;
box-sizing: content-box;
}
.fileName {
font-family: Arial;
font-size:14px;
}
.upload + .uploadButton {
height:38px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
<div class="upload">
<input type="button" class="uploadButton" value="Browse" />
<input type="file" name="upload" accept="image/*" id="fileUpload" />
<span class="fileName">Select file..</span>
</div>
<input type="button" class="uploadButton" value="Upload File" />
</form>
Hope this helps!!!
Here is a solution with a text field where the user types in the (relative) pathname of the file copy on the server (if authorized) and a submit button to browse the local system for a file and send the form:
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<p><input type="file" name="upload_file" id="upload_file" size="40"/></p>
<p><input type="text" id="upload_filename" name="upload_filename" size="30" maxlength="100" value="<?php echo htmlspecialchars($filename, ENT_COMPAT, 'UTF-8'); ?>"/>
<input type="submit" class="submit submit_upload" id="upload_upload" name="upload_upload" value="Upload"/></p>
</form>
The scripting part hides the file input, clicks it if the user clicks on the submit button, submits the form if the user has picked up a file. If the user tries to upload a file without entering a filename, the focus is first moved to the text field for the filename.
<script type="text/javascript">
var file=$('#upload_file');
var filename=$('#upload_filename');
var upload=$('#upload_upload');
file.hide().change(function() {if (file.val()) {upload.unbind('click').click();}});
upload.click(function(event) {event.preventDefault();if (!filename.val()) {filename.focus();} else {file.click();}});
</script>
Simply style the submit button for a perfect result:
.submit {padding:0;margin:0;border:none;vertical-align:middle;text-indent:-1000em;cursor:pointer;}
.submit_upload {width:100px;height:30px;background:transparent url(../images/theme/upload.png) no-repeat;}
This is my method if i got your point
HTML
<form action="upload.php">
<input type="file" id="FileInput" style="cursor: pointer; display: none"/>
<input type="submit" id="Up" style="display: none;" />
</form>
jQuery
<script type="text/javascript">
$( "#FileInput" ).change(function() {
$( "#Up" ).click();
});
</script>
When you retreive the value of an input field, browser will return a fake path (literally C:\fakepath[filename] in Chrome). So I would add the following to the Javascript solutions:
val=$('#file').val(); //File field value
val=val.replace('/','\\'); //Haven't tested it on Unix, but convert / to \ just in case
val=val.substring(val.lastIndexOf('\\')+1);
$('#textbox').val(val);
Ofc, it could be done in a single line.

Emulate a file upload click in jQuery

I have an <img ... /> tag that I have bound a click event to in jQuery. When it is clicked I'd like to have it emulate the click of a button on the file upload to open the file system browse pop-up. I've tried these things within the click function and had no success:
...
$(".hiddenUploadBtn").click();
...
...
$(".hiddenUploadBtn").select();
...
...
$(".hiddenUploadBtn").submit();
...
Just wrap the img in a label and set the for attribute to the file input. Works for any kind of content and it's built into the spec. You can even hide the file input at that point.
<input type="file" id="fileUpload"><br>
<label for="fileUpload">
<img src="https://www.google.com/images/srpr/logo11w.png" />
</label>
Try this one using only javascript:
http://code.google.com/p/upload-at-click/
Demo:
http://upload-at-click.narod.ru/demo2.html
This works for me
<input name="picture" type="file" onchange="alert(this.value)" class="file" size=20/>
for use upload button as image try this
<style>
div.fileinputs {position:relative; display:inline;}
div.fakefile {position:absolute; top:0px; left:0px; z-index:1;}
input.file {position:relative; text-align:right; -moz-opacity:0; filter:alpha(opacity: 0); opacity: 0; z-index:2;}
<style>
<div class="fileinputs">
<input name="picture" type="file" onchange="alert(this.value)" class="file" size=1/>
<div class="fakefile">
<img src="images/browse.gif" align="middle" alt="browse" title="browse"/>
</div>
</div>
so the input field is hidden, and when u click image - the selection dialog appears, but emulate this dialog from js imposible, yep.
But you can also write the plugin/hack for browser)
You can style a custom button as you wish and hide the current input file.
So when clicking at the new button, it'll fire the file upload.
$(document).ready(function(){
$('#newUploadButton').click(function(e){
e.preventDefault();
$('#formTest input[type="file"]').click();
});
});
#fileUpload { display: none; }
#newUploadButton {
background: #f2f2f2 url(images/icons/upload.png) no-repeat center left;
color: #333;
font-size: 14px;
padding: 12px 12px 12px 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="" id="formTest" name="">
<input type="file" id="fileUpload">
Upload here
</form>
The spec says it is supposed to work, and it does, on Chrome. However, Firefox and other common browsers don't follow the rules, so you're SOL.

open file select dialog with javascript [duplicate]

I'd like to make a click event fire on an <input type="file"> tag programmatically.
Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.
I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.
I have been searching for solution to this whole day. And these are the conclusions that I have made:
For the security reasons Opera and Firefox don't allow to trigger file input.
The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.
Upload File
You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:
$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();
It works with the hide before the click() but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.
THIS IS POSSIBLE:
Under FF4+, Opera ?, Chrome:
but:
inputElement.click() should be called from user action context! (not script execution context)
<input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)
just use a label tag, that way you can hide the input, and make it work through its related label
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label
For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.
HTML (Somewhere):
<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>
HTML (Somewhere you don't care about):
<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
</div>
JavaScript:
function pageY(el) {
var ot = 0;
while (el && el.offsetParent != el) {
ot += el.offsetTop ? el.offsetTop : 0;
el = el.offsetParent;
}
return ot;
}
function pageX(el) {
var ol = 0;
while (el && el.offsetParent != el) {
ol += el.offsetLeft ? el.offsetLeft : 0;
el = el.offsetParent;
}
return ol;
}
function fileMove() {
if (navigator.appName == "Microsoft Internet Explorer") {
return; // Don't need to do this in IE.
}
var link = document.getElementById("fileLink");
var form = document.getElementById("uploadForm");
var x = pageX(link);
var y = pageY(link);
form.style.position = 'absolute';
form.style.left = x + 'px';
form.style.top = y + 'px';
}
function fileBrowse() {
// This works in IE only. Doesn't do jack in FF. :(
var browseField = document.getElementById("uploadForm").file;
browseField.click();
}
Try this solution: http://code.google.com/p/upload-at-click/
If you want the click method to work on Chrome, Firefox, etc, apply the following style to your input file. It will be perfectly hidden, it's like you do a display: none;
#fileInput {
visibility: hidden;
position: absolute;
top: 0;
left: -5000px;
}
It's that simple, I tested it works!
$(document).one('mousemove', function() { $(element).trigger('click') } );
Worked for me when I ran into similar problem, it's a regular eRube Goldberg.
WORKING SOLUTION
Let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.
The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.
HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up
<div class="file-input wrapper">
<input id="inpFile0" type="file" class="file-input control" />
<div class="file-input content">
<label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
<input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
</div>
</div>
CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.
.file-test-area {
border: 1px solid;
margin: .5em;
padding: 1em;
}
.file-input {
cursor: pointer !important;
}
.file-input * {
cursor: pointer !important;
display: inline-block;
}
.file-input.wrapper {
display: inline-block;
font-size: 14px;
height: auto;
overflow: hidden;
position: relative;
width: auto;
}
.file-input.control {
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
height: 100%;
position: absolute;
text-align: right;
width: 100%;
z-index: 2;
}
.file-input.content {
position: relative;
top: 0px;
left: 0px;
z-index: 1;
}
.file-input.output {
background-color: #FFC;
font-size: .8em;
padding: .2em .2em .2em .4em;
text-align: center;
width: 10em;
}
.file-input.button {
border: none;
font-weight: bold;
margin-left: .25em;
padding: 0 .25em;
}
JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)
var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
if (inp[i].type != 'file') continue;
inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
inp[i].onchange /*= inp[i].onmouseout*/ = function () {
this.relatedElement.innerHTML = this.value;
};
};
Working jsFiddle Example
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
I know this is old, and all these solutions are hacks around browser security precautions with real value.
That said, as of today, fileInput.click() works in current Chrome (36.0.1985.125 m) and current Firefox ESR (24.7.0), but not in current IE (11.0.9600.17207). Overlaying a file field with opacity 0 on top of a button works, but I wanted a link element as the visible trigger, and hover underlining doesn't quite work in any browser. It flashes on then disappears, probably the browser thinking through whether hover styling actually applies or not.
But I did find a solution that works in all those browsers. I won't claim to have tested every version of every browser, or that I know it'll continue to work forever, but it appears to meet my needs now.
It's simple: Position the file input field offscreen (position: absolute; top: -5000px), put a label element around it, and trigger the click on the label, instead of the file field itself.
Note that the link does need to be scripted to call the click method of the label, it doesn't do that automatically, like when you click on text inside a label element. Apparently the link element captures the click, and it doesn't make it through to the label.
Note also that this doesn't provide a way to show the currently selected file, since the field is offscreen. I wanted to submit immediately when a file was selected, so that's not a problem for me, but you'll need a somewhat different approach if your situation is different.
JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/
popFileSelector = function() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
};
window.popRightAway = function() {
document.getElementById('log').innerHTML += 'I am right away!<br />';
popFileSelector();
};
window.popWithDelay = function() {
document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
window.setTimeout(function() {
document.getElementById('log').innerHTML += 'I was delayed!<br />';
popFileSelector();
}, 1000);
};
<body>
<form>
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
</form>
<a onclick="popRightAway()" href="#">Pop Now</a>
<br />
<a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
<div id="log">Log: <br /></div>
</body>
Here is pure JavaScript solution to this problem. Works well across all browsers
<script>
function upload_image_init(){
var elem = document.getElementById('file');
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
This code works for me. Is this what you are trying to do?
<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button id="addfiles" >Add files</button>
<script language="javascript" type="text/javascript">
$("#addfiles").click(function(){
$("#fileinput").click();
});
</script>
My solution for Safari with jQuery and jQuery-ui:
$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');
There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.
If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.
I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.
My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.
I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:
Create a file upload and a separate element containing an image that you want to use as the button
Arrange them to overlap and make the file element backgroud and border transparent so the button is the only thing visible
Add the javascript to make IE open the dialog when the button/file input is clicked
Use an onchange event to submit the form when a file is selected
This is only theoretical since I already used another method to solve the problem but it just might work.
I had a <input type="button"> tag hidden from view. What I did was attaching the "onClick" event to any visible component of any type such as a label. This was done using either Google Chrome's Developer Tools or Mozilla Firefox's Firebug using the right-click "edit HTML" command. In this event specify the following script or something similar:
If you have JQuery:
$('#id_of_component').click();
if not:
document.getElementById('id_of_component').click();
Thanks.
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
For AngularJS or even for normal javascript.
This will now be possible in Firefox 4, with the caveat that it counts as a pop-up window and will therefore be blocked whenever a pop-up window would have been.
Here is solution that work for me:
CSS:
#uploadtruefield {
left: 225px;
opacity: 0;
position: absolute;
right: 0;
top: 266px;
opacity:0;
-moz-opacity:0;
filter:alpha(opacity:0);
width: 270px;
z-index: 2;
}
.uploadmask {
background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
width:132px;
}
HTML with "small" JQuery help:
<div class="uploadmask">
<input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield" type="file" onchange="$('#uploadmaskfield').val(this.value)" >
Just be sure that maskfied is covered compeltly by true upload field.
You can do this as per answer from Open File Dialog box on <a> tag
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
Upload
I found that if input(file) is outside form, then firing click event invokes file dialog.
Hopefully this helps someone - I spent 2 hours banging my head against it:
In IE8 or IE9, if you trigger opening a file input with javascript in any way at all (believe me I've tried them all), it won't let you submit the form using javascript, it will just silently fail.
Submitting the form via a regular submit button may work but calling form.submit(); will silently fail.
I had to resort to overlaying my select file button with a transparent file input which works.
This worked for me:
<script>
function sel_file() {
$("input[name=userfile]").trigger('click');
}
</script>
<input type="file" name="userfile" id="userfile" />
Click
it's not impossible:
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);
But somehow it works only if this is in a function which was called via a click-event.
So you might have following setup:
html:
<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">
JavaScript:
function openFileChooser() {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function()
{
document.getElementById('input_img').dispatchEvent(evObj);
},100);
}
You can use
<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
$('#file_input').focus().trigger('click');
});
</script>
To do so you can click an invisible, pass-through element over the file input :
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}

Categories