Categories
Web Development

The Ugly Bootstrap File Input Type

Bootstrap has a way making a lot of HTML elements look good, right off the bat. But the day finally came when I had to face to inevitable: The . This is the red headed stepchild of Bootstrap (and browser makers). Browsers render this element differently from each other, making it nearly impossible to look good across the board.

Bootstrap has a way making a lot of HTML elements look good, right off the bat. But the day finally came when I had to face to inevitable: The <input type=”file”>. This is the red headed stepchild of Bootstrap (and browser makers). Browsers render this element differently from each other, making it nearly impossible to look good across the board.

Our final result should look something like this!
Our final result should look something like this!

In my initial efforts, I can across this great article from DuckRanger.com titled “Pretty file input field in Bootstrap“. For the most part, the prescribed solution did the trick. However, there were a couple of things I added to improve on it. That’s what I’ll be sharing with you.

Add A File Input Element Like This

<input type="file" name="input_name" id="file" class="sr-only" />

Note that this element has the “sr-only” class. This moves the field off screen, leaving it accessible to the visually impaired and IE users.

Add A Pretty Text Input To Take It’s Place

<div class="input-group">
  <input id="pretty-input" class="input-large" type="text" onclick="$('#file').click();">
  <span class="input-group-addon" onclick="$('#file').click();">Browse</span>
</div>

This element will act as a stand-in for the file input. But we’re not done yet.

Add jQuery To Make It Come To Life

<script type="text/javascript">
$('#file').change(function() {
  $('#pretty-input').val($(this).val().replace("C:\\fakepath\\", ""));
});
</script>

This function achieves two things. First off, it places the value of your stand-in text field into the hidden file input field. Lastly, it removes the annoying “C:\fakepath\” bit from the text input field, so it only shows the file name.

By Tim Bunch

Tim Bunch is a Web Developer from Rockaway Beach, Oregon. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

1 reply on “The Ugly Bootstrap File Input Type”

Leave a Reply