AnApprentice
AnApprentice

Reputation: 110950

Preventing a form submission with jquery ujs if the field is empty

I have a form that submits with data-remote => true.

The form has one field, a textarea. I want to prevent submission of the form if the textarea length is 0 and only allow a form submission if the length is GT 1.

How do I bind to the form in a rails 3, jquery ujs friendly way. I tried the following but that did not stop the form submissions:

 $('#new_feedback').bind('ajax:before', function() {
      e.preventDefault();
 } );

Thanks

Upvotes: 11

Views: 4891

Answers (1)

Kyle
Kyle

Reputation: 4449

You can bind directly to the form itself. This way, you can check the field you want as well as any other fields you may want to check when the form is submitted. return false is what cancels the form submission.

$('#myform').submit(function()
{
   if($('#fieldtocheck').val().length < 1)
   {
      return false;
   }
});

Upvotes: 8

Related Questions