Styling file upload button for simple_form_for with Bootstrap in Rails 3

tibbon picture tibbon · Jan 24, 2013 · Viewed 32.9k times · Source

Using simple_form_for, Bootstrap and Rails 3. In a form:

<%= f.input :upload, label: 'PDF file:' , input_html: {accept: ('application/pdf') } %>

I don't know how I'd style this so that the "choose file" button can have a different class ('btn btn-primary').

Additionally, when using with Bootstrap at least, its severely misaligned by default. See attached image.

Finally, how do I redefine the text from "No file chosen" to "Chose file" when there isn't one added yet, and show the file name when there is one.

enter image description here

Answer

BSB picture BSB · Apr 11, 2013

This is how I do it:

  1. In the view add your form file field and hide it
  2. Add a styled additional field just to display the file name
  3. Add a button to trigger the file browse dialog

    <div class="control-group">
      <div class="attach-set">
        <%= f.input :real_file, input_html: { hidden: true }, label: 'Upload Attachment' %>
        <div class="input-append">
          <input id="file-display" class="input-large uneditable-input" type="text">
          <a id="upload-btn" class="btn"><i class="icon-upload-alt"></i> Browse</a>
        </div>
      </div> <!-- /attach-set -->
    </div> <!-- /control-group -->
    
  4. In your JS (Coffee w/ jQuery shown), pass the click from the display button onto the real file input and when they select a file drop the file name in the display text field (I drop the path so that I don't see C:\FakePath....)

    $(document).ready ->
    
      # ------------------------------------------------------
      # pretty-fy the upload field
      # ------------------------------------------------------
      $realInputField = $('#real_file')
    
      # drop just the filename in the display field
      $realInputField.change ->
        $('#file-display').val $(@).val().replace(/^.*[\\\/]/, '')
    
      # trigger the real input field click to bring up the file selection dialog
      $('#upload-btn').click ->
        $realInputField.click()