How can I make a button to attach files? - javascript

I want to make a button that allows me to attach files, but what I have found is that I do it with input:
<input type="file></input>"
But I want to do it with a button using jQuery bootstrap that allows me to put any message on the button, something like:
<button btn btn-primary> Attached to me </button>
And in turn make the effect of it being pressed and changing depending on which button is selected, something like this:
Effect button pushed

This could be an approaching:
if (window.FileReader) {
$('#inputImage').change(function () {
var fileReader = new FileReader(),
files = this.files,
file;
if (!files.length) {
return;
} else {
$('#upload-file').addClass('active');
}
});
} else {
$('#upload-file').removeClass('active');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<label class="btn btn-primary" id="upload-file" title="Upload image file" for="inputImage">
<input id="inputImage" class="hide" accept="image/*" name="file" type="file">
Upload new image
</label>

Use <input type="file"></input>. I think the syntax errors are really annoying you. Also, use something like onclick="//function". I dont know css but you should make a function in javascript which will, for example, change a <button> value using document.getElementById(buttonId).innerHTML. Work your way with the design.

HTML:
<input type="file" id="test" style="display:none"/>
<button id="testbtn" class="button">Attached to me</button>
JQuery:
$('#testbtn').click(function(){ $('#test').trigger('click'); });
Any CSS you want:
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
Hope this helps.
https://jsfiddle.net/hog0rozg/

Related

Place a text inside the middle of an input

Having an input form:
.upload-image input {
height: 100% !important;
width: 100% !important;
}
.upload-image-container {
background-color: #f5f7fa;
height: 192px;
width: 320px;
}
.upload-logo-label {
font-family: Open Sans;
top: 0;
color: #afafaf;
z-index: 1;
}
<div className="upload-image upload-image-container">
<label
htmlFor="files"
className="upload-logo-label btn"
id="image-input">
Drag & drop logo here
<input
name="image"
id="image-input"
accept="image/*"
onChange={console.log('upload image')}
multiple
type="file"
className="imgInp"
/>
</label>
</div>
The problem is that the div creates first the label on top and under it the input. What I want is to place the label (or not mandatory that label but anything that can contain text) in the middle of input.
This is how it looks now:
This is how I want to make it look (ignore the icon for the moment):
Also, only the input is clickable at the moment, the label text isn't and it should be.
Is there a way to do this?
I actually didnt try it, but something very similar worked, when I made custom checkboxes for one customer. I would go for something like this...
<input name="image"
id="image-input"
accept="image/*"
onChange={console.log('upload image')}
multiple
type="file"
class="imgInp"
style="display:none" />
<div id="img-div" class="upload-image upload-image-container">
<label htmlFor="files"
class="upload-logo-label btn"
id="image-input">
Drag & drop logo here
</label>
</div>
<script type="text/javascript">
$("#img-div").on("drop", function (event) {
$("#image-input").trigger("drop", event);
});
$("#img-div").on("click", function (event) {
$("#image-input").trigger("click", event);
});
</script>

My input file is opening when I click outside of "choose file", how can I make it only open if the actual "button" is clicked?

I am using the below code to set up a file upload. However on my page, the width of the input element is greater than the actual button that shows up. I can click anywhere in this invisible box and still open the file browser. I want to just be able to click the button and open it, not blank space. How can I achieve this?
<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />
You can hide the file button, and create a fake one to mimic it. Like this:
var fakeButton = document.getElementById('fake-file-btn');
var fileButton = document.getElementById('selectFiles');
fakeButton.addEventListener('click', function(e) {
// creates a event that triggers click on fileButton
var clickEvent = new MouseEvent('click', {bubbles: true});
fileButton.dispatchEvent(clickEvent);
});
#selectFiles {
display: none;
}
<button id="fake-file-btn">Choose File</button>
<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />
Did you mean that ?
<label>
<input type="file" />
<span class="file-button">Upload File</span>
</label>
label {
display: inline-block;
}
label input[type="file"] {
display: none;
}
.file-button {
padding: 13px 20px;
color: #fff;
display: block;
cursor: pointer;
font-weight: 500;
font-size: 0.8em;
background: #f00;
}

HTML how to remove text in FileUpload field?

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

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.

Categories