I have php dynamically creating a form, and it being loaded with Ajax. Im then using jQuery Validation to check the form, but as I do not know the names of the inputs in advance, I need to add the rules after the form is loaded and before a user submits the form.
I've tried the following, but it attempts to submit the form on the first click, and then check the rules on the second.
$("#readingForm").validate({
invalidHandler: function () { //display error alert on form submit
EMPGlobal.showAlert('', '', 'danger', 'There was an error' , '', '', '', 'warning');
},
submitHandler: function (){
$('#readingForm .meter-val').each(function(){
$(this).rules( "add", {
required: true,
number: true,
minlength: 2
});
});
$('#readingForm .insert-val').each(function(){
$(this).rules( "add", {
required: true,
minlength: 10,
date: true
});
});
$.ajax({
url: 'include/pages/readings.php?',
data: $(this).serialize(),
type: 'POST',
success: function (data) {
EMPGlobal.showAlert('', '', 'success', message, '', '', '', 'success', jqXHR.status);
},
error: function (jqXHR, textStatus, errorThrown) {
returnMes = $.parseJSON(jqXHR.responseText);
message = 'A ' + jqXHR.status + ' ' + errorThrown + ' error occured. <br /> <i>Message Details: ' + returnMes + '</i>';
EMPGlobal.showAlert('', '', 'danger', message, '', '', '', 'warning', jqXHR.status);
},
});
}
});
Help on this one would be really appreciated, I've been going round in circles with this one for hours.