如何使用带有Ruby on Rails的JS提交表单

时间:2016-01-15 22:16:04

标签: javascript ruby-on-rails

我有一个使用refile gem处理文件上传的rails项目,我想在用户在文件浏览器中选择文件后提交表单。

我在rails应用的导航栏中创建了一个按钮,其格式如下。

_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>

一旦用户在文件浏览器中选择了uploadImage按钮,我想调用Open JS函数。

我在navbar_image_upload.js中创建了一个app/assets/javascripts文件,如下所示,

// app/assets/javascripts/navbar_image_upload.js

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

但是,当我在文件浏览器中选择文件并选择Open时,它不会提交表单。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您确定uploadImage未被调用吗?假设是,它提交了父表单form_upload_image

你可能并不打算嵌套表格; form_for助手会自行呈现表单标记。这是您实际想要提交的表单。

你应该看看渲染的输出。您可能拥有比预期更多的表单元素。

答案 1 :(得分:1)

您可以更好地将change方法与unobtrusive pattern绑定,因为使用内联JS几乎肯定会导致授权等问题:

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

您最好使用表单的正确格式:

<%= 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 %>