The best approach would be to have a custom label element with a for attribute attached to a hidden file input element. (The label's for attribute must match the file element's id in order for this to work).
1 - It's worth noting that if you hide the element using display: none, it won't work in IE8 and below. Also be aware of the fact that jQuery validate doesn't validate hidden fields by default. If either of those things are an issue for you, here are two different methods to hide the input (1, 2) that work in these circumstances.
Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014:
The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user.
We are the third browser to implement this change, after IE and Chrome.
According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers.
Here's a page describing the differences (basically you can put html into a <button></button>)
And another page describing why people avoid <button></button> (Hint: IE6)
Another IE problem when using <button />:
And while we're talking about IE, it's
got a couple of bugs related to the
width of buttons. It'll mysteriously
add extra padding when you're trying
to add styles, meaning you have to add
a tiny hack to get things under
control.
Best Answer
You don't need JavaScript for this! Here is a cross-browser solution:
See this example! - It works in Chrome/FF/IE - (IE10/9/8/7)
The best approach would be to have a custom label element with a
for
attribute attached to a hidden file input element. (The label'sfor
attribute must match the file element'sid
in order for this to work).As an alternative, you could also just wrap the file input element with a label directly: (example)
In terms of styling, just hide1 the input element using the attribute selector.
Then all you need to do is style the custom
label
element. (example).1 - It's worth noting that if you hide the element using
display: none
, it won't work in IE8 and below. Also be aware of the fact that jQuery validate doesn't validate hidden fields by default. If either of those things are an issue for you, here are two different methods to hide the input (1, 2) that work in these circumstances.