Ive been thinking about this for days... seems simple but I can't wrap my head around it!
We want to make a simple booking form, where people chose a day and then see two columns of available time slots. I already generate a lost of these.
Now I need to display this in buttons, so they can be pressed and only 1 is selected. So if they choose 2pm Wednesday, and then another, the first goes back to the standard color...
This value needs to be loaded in a hidden field to pass on to the next page.
Having searched it seems like the colors are best done in jquery and the hidden field can be populated easily with vanilla js, that part I have working... Help, how add the color change?
ps this is on a bootstrap 3.4 template, not that that should matter but maybe
<input type="button" id = "booktime" onclick="change(this)" class="btn btn-default" value=" & thishour & ">
function change(bookingtime) {
document.getElementById("myInput").value= bookingtime.value;
}
var links = $('#booktime');
links.click(function() {
links.css('background-color', 'white');
$(this).css('background-color', 'purple');
});
Consider the following HTML and jQuery example.
$(function() {
$(".booking label").click(function() {
var $self = $(this).parent();
$("input", $self).trigger("click");
$(".checked").removeClass("checked");
$self.addClass("checked");
});
$("form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
});
});
.booking ul {
list-style: none;
padding: 0;
width: 100px;
}
.booking li {
border: 1px outset rgb(224, 224, 224);
border-radius: 6px;
background: #eee;
padding: 7px;
text-align: center;
margin-bottom: 3px;
font-family: Arial, sans-serif;
}
.booking li.checked {
background: #aaf;
}
.booking li:hover {
background: #ccc;
}
.booking li input {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="booking">
<ul>
<li>
<input type="radio" id="time-0000" name="time" value="12:00">
<label for="time-0000">12:00 AM</label>
</li>
<li>
<input type="radio" id="time-0100" name="time" value="01:00">
<label for="time-0100">1:00 AM</label>
</li>
<li>
<input type="radio" id="time-0200" name="time" value="02:00">
<label for="time-0200">2:00 AM</label>
</li>
<li>
<input type="radio" id="time-0300" name="time" value="03:00">
<label for="time-0300">3:00 AM</label>
</li>
<li>
<input type="radio" id="time-0400" name="time" value="04:00">
<label for="time-0400">4:00 AM</label>
</li>
</ul>
</div>
<button type="submit">Save</button>
</form>
Most of the User Interface is all CSS. You can make it a bit mo9re custom and include a better look and feel with additional JavaScript. The default function of the Radio Button will help.
Radio buttons are normally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time.
This will help each button retain a State, either Checked or Unchecked. only one can be checked at a time, so we can simple clear the Styling from any other and apply it to the one clicked upon.
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.
Here is my fiddle: https://jsfiddle.net/cgz63qhd/
body {
padding: 10px;
font-family: sans-serif;
}
div.donation-levels {
margin: 3px 0;
}
.donation-level-container {
display: inline-block;
}
.donation-level-container input {
visibility: hidden;
}
.donation-level-amount-container {
text-align: center;
margin: 5px 2px;
padding: 0.7em 2em;
color: #ffffff;
background-color: #1a92b4;
border-radius: 5px;
display: inline-block;
cursor: pointer;
font-size: 22px;
}
.donation-level-amount-container:hover {
background: #e8525f;
color: #ffffff;
}
.donation-level-label-input-container input:checked~label {
background: #e8525f;
}
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
</div>
<label for="level_flexibleexpanded5942" onclick="">
<div class="donation-level-amount-container">
$35.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
</div>
</div>
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
</div>
<label for="level_flexibleexpanded5943" onclick="">
<div class="donation-level-amount-container">
$60.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
</div>
</div>
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
</div>
<label for="level_flexibleexpanded5944" onclick="">
<div class="donation-level-amount-container">
$120.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
</div>
</div>
Here is my inspiration donate page: https://action.audubon.org/donate/now
Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).
My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?
I've seen a lot of questions here on this topic but I can't seem to get anything to work.
I'm sure there are other issues in the code, please point them out if you see them!
$(".donation-level-amount-container").on("click", function() {
$('.donation-level-amount-container').each(function() {
$(this).removeClass('active');
});
$(this).toggleClass('active');
})
And css
.active {
background:#e8525f;
color:#ffffff;
}
Working fiddle:
https://jsfiddle.net/29exoa4k/2/
You need this piece of jQuery:
$(function() {
$(document).on('click','.donation-level-amount-container',function(){
$('.donation-level-amount-container').removeClass('active');
$(this).addClass('active');
});
});
Update also to this CSS:
.donation-level-amount-container:hover, .donation-level-amount-container.active {
background:#e8525f;
color:#ffffff;
}
Here is the updated jsfiddle.
You want something like this
$(".donation-level-amount-container").on("click", function() {
$(this).css("background", "red");
})
or to toggle an active class
$(".donation-level-amount-container").on("click", function() {
$(this).toggleClass("active");
})
You need this
$(".donation-level-amount-container").on("click", function() {
$(".donation-level-amount-container").css("background", "#1a92b4");
$(this).css("background", "#e8525f");
})
and css !important for background property
.donation-level-amount-container:hover {
background:#e8525f!important;
color:#ffffff;
}
here's your updated fiddle https://jsfiddle.net/cgz63qhd/3/
Indeed, this can not be done with pure CSS, since you can't traverse upward in the DOM using CSS selectors. As previous answers mentioned, it can easily be done with jQuery, but it can also be done in vanilla javascript.
var donationButtons = document.querySelectorAll('.donation-level-amount-container');
var defaultBg = '#1a92b4';
var activeBg = '#f00';
donationButtons.forEach(function(btn){
btn.onclick = function(){
donationButtons.forEach(function(btn){
// deselect previously selected buttons
btn.style.background = defaultBg;
});
this.style.background = activeBg;
}
});
I'm certain this can be done smoother, but this is the first solution that popped up in my head.
I need to create a priority field in my HTML form. Currently i am using radio buttons but it does not suffice my needs. The radio button should change background color onclick depending on the level of priority. Also i am not able to read the values to the controller.
The priority field should change colors according to the matrix above. In the form only the first row is present for the priority field.
This is the HTML i am using for priority
` <input type="radio" id="1" class="priority">
<input type="radio" id="2" class="priority">
<input type="radio" id="3" class="priority">
<input type="radio" id="4" class="priority">
<input type="radio" id="5" class="priority">`
I am using spring MVC framework.
Any help would be appreciated
UPDATE: updated FIDDLE
add value attribute to the radio buttons like
<input type="radio" name="1" id="r1" value="a rating">
then some script to read the radio button values like:
var htmlStr = $(this).attr("value");
$(".indicator").html(htmlStr);
I've tried some workaround for the sake of "changing color" in this Fiddle
Added this html, to act as the radio buttons that changes color:
<div class="circ"></div>
<div class="circ"></div>
<div class="circ"></div>
<div class="circ"></div>
<div class="circ"></div>
with this css, to take it under the radio buttons:
.circ{
height: 12px;
width: 12px;
border-radius: 50%;
background: gray;
display: inline-block;
position: relative;
bottom: 20px;
margin-left: 5px;
margin-right: 4px;
}
Then add z-index: 9 to the radio button css rule to make it stay on top of the .circ divs and be clickable. Finally, add opacity: 0 to make it invisible, so the .circ divs under will appear on screen. Now you can change the color of the .circ divs accordingly using some script.
PS: You can't just edit radio button's background color, instead use background images
I am not sure if i understud your question correct, but if so this demo code (jsfiddle) might help.
(its just a demo, and would still have to be adapted for your needs)
It simply sets the color class on the Click event of every RadioButton.
CSS
.color1 {
background:red;
}
.color2 {
background:green;
}
.color3 {
background:yellow;
}
HTML
<div class="priority">
<input type="radio" name="1" id="1">
<input type="radio" name="1" id="2">
<input type="radio" name="1" id="3">
<input type="radio" name="1" id="4">
<input type="radio" name="1" id="5">
</div>
Script
$(function () {
$(".priority input").on("click", function () {
$(".priority").attr("class", "priority color" + this.id);
});
})
tested with Chrome 34+
As per your requirement you can use jQuery plugin Colourful rating system. It comes with good options so that you can set the color as required.
DEMO
example as follows:
the HTML
<ul id="rating">
<li>This is just a piece of crap</li>
<li>Nothing too new or interesting</li>
<li>Not bad, I like it</li>
<li>I would like to see more of this</li>
<li>This is the best thing I've seen</li>
</ul>
CSS
#rating { list-style:none; }
#rating li { display:inline; float:left; }
#rating li a { display:block; width:80px; height:80px; border:1px solid #888; background-color:#333;
text-indent:-9999px; box-shadow:0 0 5px #888; border-radius:40px; }
#ratinginfo { clear:left; width:350px; }
#ratinginfo p { text-align:center; padding:10px;
box-shadow:0 0 5px #888; border-radius:40px; }
After we're done loading jQuery and the Color plugin, we're ready to use jQuery to now animate the circles to the right colour and display the text.
// Variable to set the duration of the animation
var animationTime = 500;
// Variable to store the colours
var colours = ["bd2c33", "e49420", "ecdb00", "3bad54", "1b7db9"];
// Add rating information box after rating
var ratingInfobox = $("<div />")
.attr("id", "ratinginfo")
.insertAfter($("#rating"));
// Function to colorize the right ratings
var colourizeRatings = function(nrOfRatings) {
$("#rating li a").each(function() {
if($(this).parent().index() <= nrOfRatings) {
$(this).stop().animate({ backgroundColor : "#" + colours[nrOfRatings] } , animationTime);
}
});
};
// Handle the hover events
$("#rating li a").hover(function() {
// Empty the rating info box and fade in
ratingInfobox
.empty()
.stop()
.animate({ opacity : 1 }, animationTime);
// Add the text to the rating info box
$("<p />")
.html($(this).html())
.appendTo(ratingInfobox);
// Call the colourize function with the given index
colourizeRatings($(this).parent().index());
}, function() {
// Fade out the rating information box
ratingInfobox
.stop()
.animate({ opacity : 0 }, animationTime);
// Restore all the rating to their original colours
$("#rating li a").stop().animate({ backgroundColor : "#333" } , animationTime);
});
// Prevent the click event and show the rating
$("#rating li a").click(function(e) {
e.preventDefault();
alert("You voted on item number " + ($(this).parent().index() + 1));
});
for complete documentation and source code click HERE
I'm trying to achieve this but it doesn't work.
Here it is the CSS sheet:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #000000;
}
#carte label {
border: inline-block;
cursor: pointer;
}
#carte label img {
padding: 3px;
}
the HTML part:
<div id="carte">
Select a card:<BR>
<input type=radio name="carte" id="cart1" class='input_hidden' />
<label for="cart1">
<img src="cart1.jpg" alt="carte1" />
</label>
<input type=radio name="carte" id="cart2" class='input_hidden' />
<label for="cart2">
<img src="cart1.jpg" alt="carte2" />
</label>
<input type=radio name="carte" id="cart3" class='input_hidden' />
<label for="cart3">
<img src="cart3.jpg" alt="carte3" />
</label>
</div>
and the javascript:
$('#carte label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
When I assign the selected class to an image it is ok, I see it with the black border. but it seems the javascript part to assign the class doesn't work.
I there any other way to assign the correct classes to the images?
Thanks for your support.
Are you sure you want to use jQuery?
With sane browsers you can solve it with pure css: http://jsfiddle.net/VSR86/4/
HTML:
<div id="carte">
<label>
<input type="radio" name="carte" value="cart1" >
<img src="http://placekitten.com/100/100">
</label>
...
CSS:
label input + img {
border: 10px solid transparent;
}
label input:checked + img {
border: 10px solid blue;
}
Of course some javascript fallback will be necessary for IE8 and older.
https://developer.mozilla.org/en-US/docs/Web/CSS/:checked
IE8 fix
Updated CSS:
label input.checked + img,
label input:checked + img {
border: 10px solid blue;
}
JS fallback:
if(/* this browser is IE8 or worse */){
$(document).on('click','label:has(input[type="radio"])',function(){
var $r = $(this).find('input');
adjustRadio( $r.attr('name'), $r.val(), 'checked');
});
}
function adjustRadio( name, value, className ){
// wait for other event handlers to run
setTimeout( function(){
$('input[type="radio"][name="'+name+'"]').each( function(){
var $r = $(this);
$r.toggleClass( className, $r.val() === value );
});
},1);
}
You could use the toggleClass function for some simplicity :)
http://api.jquery.com/toggleClass/
Since people are picky, here's a fiddle for you sir
http://jsfiddle.net/8B3SW/1/
$('#carte label').click(function(){
$(this).toggleClass('selected').siblings().removeClass('selected');;
});
Is there a way to style (or script) <input type=file /> element to have visible only "Browse" button without text field?
Thanks
Edit:
Just to clarify why to I need this. I'm using multi file upload code from http://www.morningz.com/?p=5 and it doesn't need input text field because it never has value. Script just adds newly selected file to collection on page. It would look much better without text field, if it's possible.
<input type="file" id="selectedFile" style="display: none;" />
<input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" />
This will surely work as I have used it in my projects.
I was having a heck of a time trying to accomplish this. I didn't want to use a Flash solution, and none of the jQuery libraries I looked at were reliable across all browsers.
I came up with my own solution, which is implemented completely in CSS (except for the onclick style change to make the button appear 'clicked').
You can try a working example here: http://jsfiddle.net/VQJ9V/307/ (Tested in FF 7, IE 9, Safari 5, Opera 11 and Chrome 14)
It works by creating a big file input (with font-size:50px), then wrapping it in a div that has a fixed size and overflow:hidden. The input is then only visible through this "window" div. The div can be given a background image or color, text can be added, and the input can be made transparent to reveal the div background:
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)
}
Let me know if there are any problems with it and I'll try to fix them.
I wasted my day today getting this to work. I found none of the solutions here working each of my scenarios.
Then I remembered I saw an example for the JQuery File Upload without text box. So what I did is that I took their example and stripped it down to the relevant part.
This solution at least works for IE and FF and can be fully styled. In the below example the file input is hidden under the fancy "Add Files" button.
<html>
<head>
<title>jQuery File Upload Example</title>
<style type="text/css">
.myfileupload-buttonbar input
{
position: absolute;
top: 0;
right: 0;
margin: 0;
border: solid transparent;
border-width: 0 0 100px 200px;
opacity: 0.0;
filter: alpha(opacity=0);
-o-transform: translate(250px, -50px) scale(1);
-moz-transform: translate(-300px, 0) scale(4);
direction: ltr;
cursor: pointer;
}
.myui-button
{
position: relative;
cursor: pointer;
text-align: center;
overflow: visible;
background-color: red;
overflow: hidden;
}
</style>
</head>
<body>
<div id="fileupload" >
<div class="myfileupload-buttonbar ">
<label class="myui-button">
<span >Add Files</span>
<input id="file" type="file" name="files[]" />
</label>
</div>
</div>
</body>
</html>
Add a label tag with for attribute assign the for attribute value to the file input button.
Now when you click the label, the browser will open up the file browse dialogue popup automatically.
Note: Hide the file input button using CSS.
Check the live demo below.
$('#imageUpload').change(function() {
readImgUrlAndPreview(this);
function readImgUrlAndPreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').removeClass('hide').attr('src', e.target.result);
}
};
reader.readAsDataURL(input.files[0]);
}
});
.hide {
display: none;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
vertical-align: middle;
cursor: pointer;
border: 1px solid #ddd;
box-shadow: 2px 2px 10px #eee;
border-radius: 4px;
}
.btn-large {
padding: 11px 19px;
font-size: 17.5px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
#imagePreview {
margin: 15px 0 0 0;
border: 2px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div clas="file_input_wrap">
<input type="file" name="imageUpload" id="imageUpload" class="hide" />
<label for="imageUpload" class="btn btn-large">Select file</label>
</div>
<div class="img_preview_wrap">
<img src="" id="imagePreview" alt="Preview Image" width="200px" class="hide" />
</div>
Hide the input-file element and create a visible button that will trigger the click event of that input-file.
Try this:
CSS
#file { width:0; height:0; }
HTML:
<input type='file' id='file' name='file' />
<button id='btn-upload'>Upload</button>
JAVASCRIPT(jQuery):
$(function(){
$('#btn-upload').click(function(e){
e.preventDefault();
$('#file').click();}
);
});
I tried to implement the top two solutions, and it ended up being a HUGE waste of time for me. In the end, applying this .css class solved the problem...
input[type='file'] {
color: transparent;
}
Done! super clean and super simple...
That's going to be very hard. The problem with the file input type is that it usually consists of two visual elements, while being treated as a single DOM-element. Add to that that several browsers have their own distinct look and feel for the file input, and you're set for nightmare. See this article on quirksmode.org about the quirks the file input has. I guarantee you it won't make you happy (I speak from experience).
[EDIT]
Actually, I think you might get away with putting your input in a container element (like a div), and adding a negative margin to the element. Effectively hiding the textbox part off screen.
Another option would be to use the technique in the article I linked, to try to style it like a button.
Fix to work in all browsers
RESOLVED:
<input type = "button" value = "Choose image"
onclick ="javascript:document.getElementById('imagefile').click();">
<input id = "imagefile" type="file" style='visibility: hidden;' name="img"/>
I have tested in FF, Chrome & IE - working fine, applied styles too :D
Here is my good ol' remedy:
<input type="file" id="myFile" style="display:none;" />
<button type="button" onclick="document.getElementById('myFile').click();">Browse</button>
At least it worked in Safari.
Plain and simple.
Another easy way of doing this. Make a "input type file" tag in html and hide it. Then click a button and format it according to need. After this use javascript/jquery to programmatically click the input tag when the button is clicked.
HTML :-
<input id="file" type="file" style="display: none;">
<button id="button">Add file</button>
JavaScript :-
document.getElementById('button').addEventListener("click", function() {
document.getElementById('file').click();
});
jQuery :-
$('#button').click(function(){
$('#file').click();
});
CSS :-
#button
{
background-color: blue;
color: white;
}
Here is a working JS fiddle for the same :- http://jsfiddle.net/32na3/
I used some of the code recommended above and after many hours of waisting my time, I eventually came to a css bag free solution.
You can run it over here - http://jsfiddle.net/WqGph/
but then found a better solution - http://jsfiddle.net/XMMc4/5/
<input type = "button" value = "Choose image #2"
onclick ="javascript:document.getElementById('imagefile').click();">
<input id = "imagefile" type="file" style='display:none;' name="img" value="none"/>see jsfiddle code for examples<br/>
You could label an image so when you click on it the click event of the button will be triggered. You can simply make the normal button invisible:
<form>
<label for="fileButton"><img src="YourSource"></label> <!--You don't have to put an image here, it can be anything you like-->
<input type="file" id="fileButton" style="display:none;"/>
</form>
It worked for me on all browsers, and is very easy to use.
You can dispatch the click event on a hidden file input like this:
<form action="#type your action here" method="POST" enctype="multipart/form-data">
<div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" >Click to upload!</div>
<!-- hide input[type=file]!-->
<div style='height: 0px;width:0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
<input type="submit" value='submit' >
</form>
<script type="text/javascript">
var btn = document.getElementById("yourBtn");
var upfile = document.getElementById("upfile");
btn.addEventListener('click',function(){
if(document.createEvent){
var ev = document.createEvent('MouseEvents');
ev.initEvent('click',true,false);
upfile.dispatchEvent(ev);
}else{
upfile.click();
}
});
</script>
HTML:
<input type="file" name="upload" id="upload" style="display:none"></input>
<button id="browse">Upload</button>
JQUERY
$(document).ready(function(){
$("#browse").click(function(){
$("#upload").click();
});
});
Hope this works :)
This HTML code show up only Upload File button
<form action="/action_page.php">
<input type="button" id="id" value="Upload File" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file" onchange="this.form.submit()"/>
</form>
You can give the input element a font opacity of 0. This will hide the text field without hiding the 'Choose Files' button.
No javascript required, clear cross browser as far back as IE 9
E.g.,
input {color: rgba(0, 0, 0, 0);}
Ive a really hacky solution with this...
<style type="text/css">
input[type="file"]
{
width: 80px;
}
</style>
<input id="File1" type="file" />
The problem is the width attribute that is hiding the text field will obvously vary between browsers, vary between Windows XP themes and so on. Maybe its something you can work with though?...
I know this is an old post but a simple way to make the text dissapear is just to set text color to that of your background.
eg if your text input background is white then:
input[type="file"]{
color:#fff;
}
This will not effect the Choose File text which will still be black due to the browser.
There is a simple and hacky way to show only the file input button while keeping the render and translations of this file input button :
Make the text that is displayed after a file input invisible using a the color transparent.
<input type="file" style="color: transparent" />
my solution is just to set it within a div like "druveen" said, however i ad my own button style to the div (make it look like a button with a:hover) and i just set the style "opacity:0;" to the input. Works a charm for me, hope it does the same for you.
This works for me:
input[type="file"] {
color: white!important;
}
I just styled an input file with width: 85px, and the text field disappeared at all
Select Logo <input type="file" id="logo">
$("#logo").css('opacity','0');
$("#select_logo").click(function(){
$().trigger('click');
return false;
});
For me, the simplest way is using a font color like background color. Simple, not elegant, but usefull.
<div style="color:#FFFFFF"> <!-- if background page is white, of course -->
<input class="fileInput" type="file" name="file1"/></div>
So here's the best way to do this FOR ALL BROWSERS:
Forget CSS!
<p>Append Image:</p>
<input type="button" id="clickImage" value="Add Image" />
<input type="file" name="images[]" id="images" multiple />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" charset="utf-8"></script>
<script>
$('#images').hide();
$('#clickImage').click( function() {
$('#images').trigger('click');
});
</script>
All these answers are cute, but CSS won't work since it isn't the same across all browsers and devices, the first answer I wrote will work in everything but Safari. To get it to work accross all browsers all the time it must be created dynamically and recreated every time you want to clear the input text:
var imageDiv = document.createElement("div");
imageDiv.setAttribute("id", "imagediv");
imageDiv.style.cssText = 'position:relative; vertical-align: bottom;';
var imageText = document.createTextNode("Append Image:");
var newLine = document.createElement("br");
var image = document.createElement("input");
image.setAttribute("type", "file");
image.setAttribute("id", "images");
image.setAttribute("name", "images[]");
image.setAttribute("multiple", "multiple");
imageDiv.appendChild(imageText);
imageDiv.appendChild(newLine);
imageDiv.appendChild(image);
questionParagraph.appendChild(imageDiv);
The answer of tmanthey is quite good, except that you can't play with border-width in Firefox v20. If you see the link (demo, can't really show here) they solved the problem using font-size=23px, transform:translate(-300px, 0px) scale(4) for Firefox to get the button bigger.
Other solutions using .click() on a different div is useless if you want to make it a drag'n'drop input box.
There are several valid options here but thought I would give what I have come up with while trying to fix a similar issue. http://jsfiddle.net/5RyrG/1/
<span class="btn fileinput-button">
<span>Import Field(s)</span>
<input id="fileupload" type="file" name="files[]" onchange="handleFiles(this.files)" multiple>
</span>
<div id="txt"></div>
function handleFiles(files){
$('#txt').text(files[0].name);
}
I wrote this:
<form action='' method='POST' name='form-upload-image' id='form-upload-image' enctype='multipart/form-data'>
<div style="width: 0; height: 0; overflow: hidden;">
<input type="file" name="input-file" id="input-file" onchange="this.files.length > 0 ? document.getElementById('form-upload-image').submit():null;" />
</div>
</form>
<img src="image.jpg" style="cursor: pointer;" onclick="document.getElementById('input-file').click();" />
Work fine in all browsers, no jQuery, no CSS.
Here is a simplified version of #ampersandre's popular solution that works in all major browsers.
Asp.NET markup
<asp:TextBox runat="server" ID="FilePath" CssClass="form-control"
style="float:left; display:inline; margin-right:5px; width:300px"
ReadOnly="True" ClientIDMode="Static" />
<div class="inputWrapper">
<div id="UploadFile" style="height:38px; font-size:16px;
text-align:center">Upload File</div>
<div>
<input name="FileUpload" id="FileInput" runat="server"
type="File" />
</div>
</div>
<asp:Button ID="UploadButton" runat="server"
style="display:none" OnClick="UploadButton_Click" />
</div>
<asp:HiddenField ID="hdnFileName" runat="server" ClientIDMode="Static" />
JQuery Code
$(document).ready(function () {
$('#UploadFile').click(function () {
alert('UploadFile clicked');
$('[id$="FileInput"]').trigger('click');
});
$('[id$="FileInput"]').change(function (event) {
var target = event.target;
var tmpFile = target.files[0].name;
alert('FileInput changed:' + tmpFile);
if (tmpFile.length > 0) {
$('#hdnFileName').val(tmpFile);
}
$('[id$="UploadButton"]').trigger('click');
});
});
css code
.inputWrapper {
height: 38px;
width: 102px;
overflow: hidden;
position: relative;
padding: 6px 6px;
cursor: pointer;
white-space:nowrap;
/*Using a background color, but you can use a background image to represent
a button*/
background-color: #DEDEDE;
border: 1px solid gray;
border-radius: 4px;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
user-select: none;
}
Uses a hidden "UploadButton" click trigger for server postback with standard . The with "Upload File" text pushes the input control out of view in the wrapper div when it overflows so there is no need to apply any styles for the "file input" control div. The $([id$="FileInput"]) selector allows section of ids with standard ASP.NET prefixes applied. The FilePath textbox value in set from server code behind from hdnFileName.Value once file is uploaded.