Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a remote form from submitting?

I have a form that can be used both remotely and normally.

= form_for @comment, html: { class: 'comment-form' }, remote: request.xhr? do |f|
  = f.text_area :body
  = f.submit

I want the form to submit only if the body textarea has content:

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

That code works when the form is not Ajax. But when it's remote, it fails and the form still submits. Why? I also tried:

if text.length < 1
  e.preventDefault()
  false

I'm using Rails 4 with Turbolinks.

Update: I tried binding the ajax:beforeSend event, it still submits:

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

I see no alert...

like image 860
user2630970 Avatar asked Aug 28 '13 14:08

user2630970


People also ask

How do I stop a form from submitting?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.

How do I stop a form from refreshing after submitting?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How do you prevent form submit on Enter in JavaScript?

What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript: $(document). ready(function() { $(window). keydown(function(event){ if(event.

How Stop form submit in Ajax?

If you want to prevent the default post method for the form's submit button, I suggest you could consider using the event. preventDefault() method. More details, you could refer to below codes: <form id="user-form" method="post">


1 Answers

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

like image 172
lmjohns3 Avatar answered Oct 20 '22 11:10

lmjohns3