How do I stop a remote form from submitting?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 08:30:07
lmjohns3

You could potentially implement a handler for the ajax:beforeSend event to prevent your form from being submitted. It looks like the submit stops if your event handler returns false.

Wiki: https://github.com/rails/jquery-ujs/wiki/ajax

Example implementation: Stop $.ajax on beforeSend

I'm using Rails 5.0.0.1 and as described at jquery-ujs documentation in Stoppable events section you only need to return a false value in the ajax:beforeSend event to stop the request and prevent the form from being send.

So this works perfectly for me:

$(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;
    }
});

I hope it could be useful for somebody else.

Maybe I didn't get your question, but shouldn't it be enough to add a

:required => true

to your text_area ?

This looks like a jquery_ujs issue. Try changing the event to:

 $('.comment-form').on 'submit', (e) ->

I'm facing the same issue and only this solved the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!