如何阻止远程表单提交?

use*_*970 6 jquery ruby-on-rails coffeescript ujs ruby-on-rails-4

我有一个可以远程和正常使用的表单.

= form_for @comment, html: { class: 'comment-form' }, remote: request.xhr? do |f|
  = f.text_area :body
  = f.submit
Run Code Online (Sandbox Code Playgroud)

我希望表单仅在bodytextarea具有内容时提交:

  $(document).on 'submit', '.comment-form', (e) ->
    text = $(this).find('#comment_body').val()
    false if text.length < 1
Run Code Online (Sandbox Code Playgroud)

当表单不是Ajax时,该代码有效.但是当它处于远程状态时,它会失败并且表单仍然会提交.为什么?我也尝试过:

if text.length < 1
  e.preventDefault()
  false
Run Code Online (Sandbox Code Playgroud)

我正在使用带有Turbolinks的Rails 4.

更新:我尝试绑定ajax:beforeSend事件,它仍然提交:

  $(document).on 'page:load', '.comment-form', ->
    $(this).bind 'ajax:beforeSend', ->
      alert "hi"
Run Code Online (Sandbox Code Playgroud)

我看不到警报......

ale*_*aio 5

我正在使用Rails 5.0.0.1,如jquery-ujs文档中可停止事件部分所述,您只需要在事件false中返回一个值ajax:beforeSend即可停止请求并阻止发送表单。

所以这对我来说非常有效:

$(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;
    }
});
Run Code Online (Sandbox Code Playgroud)

我希望它对其他人有用。


Mio*_*tsu 0

也许我没有明白你的问题,但添加一个就足够了

:required => true
Run Code Online (Sandbox Code Playgroud)

到你的text_area