Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 954
AnApprentice Avatar asked Aug 09 '11 17:08

AnApprentice


1 Answers

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;
   }
});
like image 147
Kyle Avatar answered Oct 02 '22 14:10

Kyle