I'm having an issue with the state of a returned variable. I have the function "altFormValidate". Essentially the issue is that when I call it, if the honeypot count is 0, the validation runs fine, and the "validationResult" variable returns true, but if the honeypot count is more than 0, the "validationResult" variable still returns false, even after executing code that should make it true.
function altFormValidate(intendedFormID){ //Validate honeypot traps
var validationResult = false;
}
var honeyPotFields = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"];
var honeyPotCount = 0;
honeyPotFields.forEach(function(entry) { //Check page for honeypots filled out
if($('#' + entry).length >= 1){
var honeyPotVal = $('#' + entry).val();
if (honeyPotVal !== ""){
honeyPotCount = honeyPotCount + 1; //Count successful honeypot traps
}
}
});
if (!honeyPotCount > 0) //Check honeypot count
{
$('#' + intendedFormID).attr("action", formAction); //Append SF action to form
validationResult = true;
}
else
{
if (honeyPotCount == 1){ //If one honeypot filled in
//SUSPECT - implement further checks
$.colorbox({ //init popup with confirmation input: "#machine-check"
href: "/inc/form-confirmation.html",
transition: "elastic",
speed: 350,
opacity: 0.65,
className: "seg-window",
onComplete: function() {
jQuery('#colorbox').find('a.btn-close, a.close, a.cancel').unbind('click.closeColorbox').bind('click.closeColorbox', function(e) {
jQuery.colorbox.close();
e.preventDefault();
});
jQuery('#machine-check').bind('change', function(e) {
jQuery.colorbox.close();
e.preventDefault();
validationResult = true; //This code doesn't seem to change the variable "validationResult" when I call the entire function altFormValidate but I know that changing "machine-check" does change the variable.
});
}
});
}
else if (honeyPotCount == 2){ //If two honeypots filled in
//PRIME SUSPECT - init Captcha/Akismet etc
alert("Robot Alert!");
validationResult = false;
}
} return validationResult;
}
and I call above function like so, on submit of the form:
var req = true;
if(req){ //If required fields are filled in
var extraValidation = altFormValidate('WebToLeadForm', 'webToLeadPost');
if (extraValidation == true){
alert("form sent");
//document.WebToLeadForm.submit();
return true;
}
}
So my question is why does extraValidation() return true if no honeypots are found, but false if one is found but the relevant code is then executed to make it true? I am thinking the issue is where I return the validationResult variable.
changehandler for#machine-checkwill fire long afteraltFormValidatehas returned.altFormValidatea callback it should call when it knows the final value, and AJAX-ically submit the form values inside that callback. Look into how asynchronous workflow works in general.