如何阻止远程表单提交?
我有一个可以远程和正常使用的表单。
= form_for @comment, html: { class: 'comment-form' }, remote: request.xhr? do |f| = f.text_area :body = f.submit
我希望表单仅在body
textarea具有内容时才提交:
$(document).on 'submit', '.comment-form', (e) -> text = $(this).find('#comment_body').val() false if text.length < 1
当表单不是Ajax时,该代码有效。 但是当它处于远程状态时,它会失败并且表单仍然会提交。 为什么? 我也尝试过:
if text.length < 1 e.preventDefault() false
我正在使用带有Turbolinks的Rails 4。
更新:我尝试绑定ajax:beforeSend
事件,它仍然提交:
$(document).on 'page:load', '.comment-form', -> $(this).bind 'ajax:beforeSend', -> alert "hi"
我看不到警报……
您可以为ajax:beforeSend
事件实现处理程序,以防止提交表单。 如果事件处理程序返回false
,则看起来提交会停止。
Wiki: https : //github.com/rails/jquery-ujs/wiki/ajax
示例实现: 在beforeSend上停止$ .ajax
我正在使用Rails 5.0.0.1
,如在Stoppable事件部分的jquery-ujs文档中所述,您只需要在ajax:beforeSend
事件中返回false
值以停止请求并阻止表单发送。
所以这对我很有用:
$(document).on("ajax:beforeSend", "form#messages_form", function (e, data, status, xhr) { var len = $.trim($('#message_body').val()).length; if (len > 3) { console.log("Send form!"); return true; } else { console.log("Stopping request..."); return false; } });
我希望它对其他人有用。
也许我没有得到你的问题,但是不应该添加一个
:required => true
你的text_area
?
这看起来像是一个jquery_ujs问题。 尝试将事件更改为:
$('.comment-form').on 'submit', (e) ->
我面临着同样的问题,只有这样才能解决问题。