1

I have a rails project that is using the refile gem to process file uploading, and I would like to submit a form after the user has selected the file in their file browser.

I created a button in the navbar of the rails app, and have the following form.

_nav.html.erb

<div class='upload-image'>
          <form name="form_upload_image">
          <p>Upload Image <i class="fa fa-upload"></i></p>
        <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |form| %>

              <%= form.attachment_field :tshirt_image, direct: true, class: "fa fa-upload", input_html: { hidden: true, onchange: "uploadImage()" } %>

          <%= form.submit "Update", class: "btn btn-primary" %>

        <% end %> <!-- form -->
      </form>
        </div>

I would like to call the uploadImage JS function once the user has selected the Open button within the file browser.

I created a navbar_image_upload.js file within the app/assets/javascripts which looks like the following,

// app/assets/javascripts/navbar_image_upload.js

function uploadImage() {
  document.forms["form_upload_image"].submit();
}

However, when I select the file in the file browser and choose Open it's not submitting the form. Any help would be appreciated.

2 Answers 2

1

You'll be better binding your change method with an unobtrusive pattern, as using inline JS is almost certainly going to lead to issues with delegation etc:

#app/assets/javascripts/application.js
$(document).on("change", "input.fa-upload", function(e){
    $(this).parents('form').submit();
});

You'll also be best to use the correct formatting for the form:

<%= content_tag :div, class: 'upload-image' do %>
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |form| %>
        <%= form.attachment_field :tshirt_image, direct: true, class: "fa fa-upload", input_html: { hidden: true } %>
        <%= form.submit "Update", class: "btn btn-primary" %>
    <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

1

Are you sure uploadImage is not being called? Assuming it is, it's submitting the parent form, form_upload_image.

You probably didn't intend to nest forms; the form_for helper renders a form tag itself. That is the form you actually want to submit.

You should take a look at the rendered output. You probably have more form elements than you expect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.