rails 4 表单提交为 div,验证无效

rails 4 form submit as div, validation not working

我在尝试使用 div(而不是 f.submit 按钮)提交表单时遇到问题

<%= form_for @user, url: {action: "submit_user"}, html: {id: "user_submit", class: "form"}, :method => "post" do |f| %>
     <%= f.text_field :first name, :required => true, :placeholder => 'first name', :autocomplete => :off %>
     <%= f.text_field :last name, :required => true, :placeholder => 'last name', :autocomplete => :off %>
     <div id="submituser" class="some very fancy css here" onclick = "document.forms['user_submit'].submit();">
<% end %>

问题是表单 已发送 ,但 没有验证 (导致它发送空白的名字和姓氏,如果没有已输入)

注意使用时

<% f.submit "submit" %>

验证确实有效。

谢谢

我想 document.forms['user_submit'].submit(); 不会触发提交事件,所以您必须手动启动验证。但是使用 div 而不是 button 有什么意义呢?您也可以使用 some very fancy css here 设置按钮样式。或者制作一个 'hidden' 提交按钮并将 onclick = "document.form.button.click()" 添加到 div :-)

在这里找到我的答案: Difference between handling $(“form”).submit or an click event?

我引用@Giovanni Sferro:

The click callback is called only if the user actually click on the submit button. But there are cases in which you would submit the form automatically by javascript, in that case the click callback is not fired while the submit callback is. I would recommend to use always the submit for validation and intrinsic action of the form, while using the click callback for animation or other things related to the action of clicking on the button.

所以我的(工作)代码如下所示:

<div id="submituser" class="some very fancy css here" onclick = '$("#user_submit input[type=\"submit\"]").click();'>