JavaScript bit:
$(document).ready(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
var $form = $(this);
// check if the input is valid
if(! $form.valid()) return false;
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
})
});
HTML bit:
<input type="text" name="answer[1]" class="required" />
<input type="text" name="answer[2]" class="required" />
So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?
Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.
I show/hide questions as I go through it in "pages".
<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>
JS:
function toggleVisibility(newSection)
{
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
beforeSubmit
as a valid option for $.ajax in the latest version of jquery (v1.7.2). You may want to use the latest version of jquery. That said, Darin's answer is how it ought to be done. That said, if you just can't do what he is suggesting, then replace the last line of your beforeSubmit with the code Fliespl has put up. You need to check the return value of.validate()
and accordingly either proceed with or cancel ajax request. – Amith George