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...
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.
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.
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.
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">
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With