2

To hide (but retain the functionality) the ugly default input type file button for file dialog I used the following mechanism:

HTML:

    <label for="file-input">
        <i class="fa fa-edit"></i> <!-- acts as file input on click-->
    </label>
    <input type="file" id="file-input" />

CSS:

#file-input {
    display: none; //hide the file input
}

This is working expectedly: I click on the font awesome edit icon and the file dialog pops up.

However, when I use a button it stops working. I get no file dialog on clicking the button:

    <label for="file-input">
        <button type="button">Upload file</button> <!-- not working-->
    </label>
    <input type="file" id="file-input" />
vishuB
  • 3,998
  • 5
  • 28
  • 47
Tarun Dugar
  • 8,731
  • 7
  • 39
  • 74

2 Answers2

5

The Label represents a "caption" for an item in a user interface. The reason why your button isn't working is because a button isn't considered a valid "caption" for a "control" element because it is a "control" element. (see: https://developer.mozilla.org/nl/docs/Web/HTML/Element/label)

If you use an image or a piece of text inside the label it will work, because that will be considered a caption (this is why your first attempt worked). If you want to create a custom button you can use some text or an image tag otherwise you'll need some javascript.

Edit: maybe this page can be of help: http://webmuch.com/how-to-customize-a-file-upload-button-using-css3-html5-and-javascript/ The javascript they use shows the user what file (s)he has selected

Nathan
  • 161
  • 2
  • 7
-3

Just change the jQuery code and HTML tag will be as it is.

    <label for="file-input">
        <button class="upload_file" type="button">Upload file</button> <!-- not working-->
    </label>
    <input type="file" id="file-input" />

Jquery Code:

jquery("[for=file-input] .upload_file").on("click", function(){
    jQuery("#file-input").trigger("click");
})
Nisse Engström
  • 4,636
  • 22
  • 26
  • 40
Harsh Sanghani
  • 1,654
  • 1
  • 11
  • 32