rails项目中有一个上传图片的功能要实现,遇到了要点击上传图片和提交表单两个按钮,这样影响用户体验,所以就想找一种方式当点击上传图片按钮以后会自动提交form表单,而不用在点击表单的提交按钮了。
<%= form_for @photo,:url => { :action => "create", :controller=>"photos" },:method => :post, :html => {:multipart => true} do |f| %>
<%= f.error_messages %>
<%= f.hidden_field :user_id %>
<%= f.label :remote_photo_name %>
<%= f.text_field :remote_photo_name %>
<%=image_tag(@user.photos.first.image_url(:thumb), alt: @user.photos.first.image,:size => "100x100" ) %><br/>
<%= f.file_field :image,:onchange => 'this.form.submit()' %>
<%= f.submit %>
<% end %>
重点在于第七行onchange的调用,但点击了上传图片以后会出发onchange ,这个表单会自动提交给create的action
另外还可以实现为了避免重复提交表单,rails中的submit_tag很好的选项disable_with
submit_tag "提交", :disable_with => "提交中..."
例如 <%= f.submit:disable_with => "提交中..."%>当用户按下"提交"按钮将会禁止再次点击提交,按钮就会变成"提交中...",