rakela
rakela

Reputation: 303

Can't submit the form after validating with jquery (using preventDefault())

<script type="text/javascript">
$(document).ready(function(){
$('#addprojectform').live('submit', function (e) {
    e.preventDefault();
     $(".error").remove();   

    var startdate = $("#startdate").val();
    var client = $('#client').val();
    var source_lang= $('#source_lang option:selected').length;
    var targ_lang = $('#targ_lang option:selected').length;
    var qty = $('#qty').val();

    var hasError = false;

   if(startdate == '') {
  $("#startdate").after('<span class="error" style="color: red;">This field is     required.</span>');
  hasError = true;
}

if(client == '') {
  $("#client").after('<span class="error" style="color: red;">This field is required.  </span>');
  hasError = true;
}

if(!(source_lang)) {
  $("#source_lang").after('<span class="error" style="color: red;">This field is required.</span>');
  hasError = true;
}

if(!(targ_lang)) {
  $("#targ_lang").after('<span class="error" style="color: red;">This field is required.</span>');
  hasError = true;
}
if(qty == '') {
  $("#qty").after('<span class="error"  style="color: red;">This field is required.</span>');
  hasError = true;
}
} // if translation


if(hasError == false)
 return true;
    });

 });
 </script>

I had this code. I want to validate the form before submission. I can't control when the form has no errors. I want to submit the form if there are no errors found. I added this code:

if(hasError == false)
 return true;

but doesn't submit the form.. Please anyone can help?

Upvotes: 0

Views: 1547

Answers (2)

Gavin
Gavin

Reputation: 6394

What I do, although it may not be fantastic is:

$('#form').submit(function(e) 
{
    if(!$(this).hasClass('valid'))
    {
        e.preventDefault();
        var isValid = false;
        // do validation to set isValid true or false;
        if(isValid)
        {
            $(this).addClass('valid');
            $(this).submit();
            // or possibly $(this).addClass('valid').submit();
            return;
        }
    }
});

How this works is, first time you submit, it checks to see if the form has a class called valid. If not, it stops the form validation and does validation.

If it's valid, it will add the class to the form and resubmit. As the form now has the valid class, it will bypass validation and submit normally.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

remove

e.preventDefault();

and change

if(hasError == false)
   return true;
});

into

return !hasError;

as a side note, live() is deprecated in favour of on() on newer jQuery version

Upvotes: 1

Related Questions