I've looked at this How-do-i-return-the-response-from-an-asynchronous-call and at why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron , but what I'm trying to do doesn't work.
Since some of our users use IE, it seems that we would have to rely on callbacks.
The background to this question comes from a previous post. Legacy code used VBscript's MsgBox, but now the same functionality must be ported to Javascript.
To provide context, there is a bunch of buttons on a toolbar (hence toolbar.asp) such as "New", "Update", "Delete". The user can navigate to certain parts of the system and for instance create a "New" record for a particular resource/person. The details and functionality are shown on the main part of the screen (hence main.asp).
The system was originally written about 15 years ago (or more).
When the user clicks "Update" on the toolbar.asp, it depends which screen the main.asp was showing. Parts of dovalidation() in main.asp can be swopped (as in a script is fetched from the database) and inserted into dovalidation() depending on what & where the user is.
So some parts are still in Visual Basic 6, but it seems that they are trying to replace the VBscript with Javascript.
So the user is on a specific screen and clicks Update (the toolbar.asp's doupdate() is called).
This doupdate() does a number of checks on the date and other variables and the calls the main.asp's dovalidation().
Depending on where the user finds himself, dovalidation looks different.
In quite a few cases as in the specific example that I am talking about, there used to be a MsgBox in the VBscript code which gave the user a choice depending on the validation done up to that point. However, that VBscript should now be replaced by Javascript. It seems my boss doesn't want to use the normal window.confirm, because she wants to be able to customise the buttons.
VBscript's MsgBox blocked further execution, but now using a jquery confirm doesn't have the same results, because it is non-blocking.
If the validation occurs in such a way that the user is provided with the confirm dialog, and the user clicks on 'Cancel' then the next page should not be shown, but at present, whether the user clicks on 'Cancel' or not, the next page is shown after a couple of seconds.
At the end of the doupdate() function there is:
parentMain.screenform.submit();
Could that be part of why my callbacks don't work?
In a toolbar.asp file, this is called in the doupdate() funtion:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
var sErr = parentMain.dovalidation();
if (sErr != ""){
return;
}
//Then the rest of the code which is executed irrespective of the jquery confirm.
//do update
try {
parentMain.document.all("Updating").value = "YES"
parentMain.document.body.scrollTop = 0
parentMain.document.body.scroll = 'no'
parentMain.ShowBusy();
document.getElementById("sysBusy").value = "true";
//parentMain.document.all("clockFrame").style.display = "block";
} catch(e) {
return (e)
}
//do check for resource tag
if (sScreenType.toUpperCase() == "RESOURCE TABLE") {
if (lResource == "0") {
parentMain.document.all("sysresource").value = lDetailResource
}
//alert("looping for resource tag");
var sField = ""
var sCheck = "Resource Tag"
if (!(sScreen == "Resource")) {
/*********************************************************************/
/** loop through the fields and update resouce tag if empty - submit**/
/*********************************************************************/
var elements = parentMain.document.getElementById("screenform").elements;
for (var i = 0, element; element = elements[i++];) {
if ((element.name).indexOf(sCheck) > 0) {
var sValue = element.value
if (sValue.length == 0) {
element.value = lDetailResource
}
}
if ((element.tagName.toUpperCase()) == "SELECT") {
if (element.disabled == true) {
element.disabled = false;
}
}
}
}
}
//submit screen
parentMain.screenform.submit(); //<-- Could this be part of the problem?
}
In the main.asp file the dovalidation function resides. A part of the dovalidation function is swapped out depending on the situation. That is marked between the //################
function dovalidation() {
msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate="";
var vLastRunDate="";
var sStatus="";
var vMsg="";
var sResponse="";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0 ){
sStatus = "SUCCESFUL";
//document.getElementById("Smoke.Calc Status").value= sStatus;
}
if ((vEffectiveDate).length > 0 ){
if (!isDate(vEffectiveDate) ){
vMsg = vMsg+"[Effective Date] Is not a date." + ";\r\n";
} else if ( moment( toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate)) ){
vMsg = vMsg+"[Effective Date] cannot be on/before "+vLastRunDate+"." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content:"Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse= "1";
vMsg = "Response 1";
processMessage(); // <--- added this
},
cancel: function() {
sResponse= "2";
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function () {
document.getElementById("Smoke.Calc Status").value= "REFRESH";
msErr = "ABORT";
processMessage(); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage();
}
function processMessage() {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg != "") {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
}
}
//#################
return msErr;
}
So I think my problem lies with msErr being returned long before the user has had chance to decide which button on the confirm dialog to choose. If I don't set breakpoints and click on the confirm's cancel then I do see that the alerts are shown, but the page is not refreshed (document.getElementById("Smoke.Calc Status").value= "REFRESH";) and the next page is shown. I think this comes from the sErr == "" in the toolbar.asp file and then the program flow just continues.
Anycase, I tried using callbacks, but the situation hasn't changed.
Here is what I tried to do:
parentMain.dovalidation(function(result){
if (result != ""){
return;
}
});
In main.asp the dovalidation function:
function dovalidation(callback) {
msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate="";
var vLastRunDate="";
var sStatus="";
var vMsg="";
var sResponse="";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0 ){
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value= sStatus;
}
if ((vEffectiveDate).length > 0 ){
if (!isDate(vEffectiveDate) ){
vMsg = vMsg+"[Effective Date] Is not a date." + ";\r\n";
} else if ( moment( toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate)) ){
vMsg = vMsg+"[Effective Date] cannot be on/before "+vLastRunDate+"." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content:"Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse= 1;
vMsg = "Response 1";
processMessage(); // <--- added this
},
cancel: function() {
sResponse= 2;
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function () {
document.getElementById("Smoke.Calc Status").value= "REFRESH";
msErr = "ABORT";
processMessage(); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage();
}
function processMessage() {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg != "") {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
}
}
//#################
callback(msErr);
}
So, it isn't working as it should, and I don't know what I've done wrong, but I suppose I haven't used the callbacks correctly.
Does it make a difference that it is in two different files?
This has to work given that the parts between the //######### are swopped.
I would appreciate any feedback and guidance.
Well, ok. I started to write a comment, but it is too small for all I need to say, so I will continue in an answer.
I see you added some more code, but... you know, your code are blowing my mind =) what you are trying to do is to get spaghetti-code and make it async.
Throw this away and let's go to the upper level. We call it "program on an interface level".
Example: replace all your big code blocks with functions (with correct name). Like code between //################# will be converted to
function dovalidation(callback) {
msErr = getValidationResult();
callback(msErr);
}
What do I do here is just throw away all your low-level code, because your problem is in the order of execution.
But this is just the first step of converting your code to something other. Next step is realizing that our "virtual" function getValidationResult has some $.confirm and $.alert inside, so it is async. That's why we need to use getValidationResult as async. Two possible ways - convert to Promise or use callbacks. Let's use callbacks. Then our simplified code will convert to:
function dovalidation(callback) {
getValidationResult(callback);
}
That is what I was trying to show on my previous answer.
And now you've added some more code with such a comment: //Then the rest of the code which is executed irrespective of the jquery confirm.. Ok, good, we will name all this code as theRestOfTheCodeIrrespectiveToConfirm(). So your original function call will be converted from this:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
var sErr = parentMain.dovalidation();
if (sErr != ""){
return;
}
theRestOfTheCodeIrrespectiveToConfirm();
to this:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
parentMain.dovalidation(sErr => {
if (sErr != ""){
return;
}
theRestOfTheCodeIrrespectiveToConfirm(); // <- this will execute only if sErr is empty
});
Am I going to the right direction?
P.S. One thing to ask you - why do you have } in the end of you example code, but no correcsponding {?
Maybe you show us not all code?
There is no need to involve jQuery.
JavaScript has the functions alert, confirm and prompt which are synchronous (i.e. blocking execution until they return) just like MsgBox was.
So if this is easier to you, you can keep your original code structure this way. Because as it was explained in the "how do I return a response from an asynchronous call" article, you cannot make the dovalidation function return anything that depends on the result of an asynchronous operation like the $.confirm that you currently use, since that would require time travel ;) - but you can make it dependent on synchronous operations like JS' built-in confirm.
You are mixing sync code with async... Because $.confirm is async, but you call dovalidation as sync.
Note: your code is very strange, maybe because of small JS experience, so I will try to guess what you need. You can ask if something in my code is incorrect.
Your second example with callback is more close to working solution, but you need to call the callback only if you know the user's answer.
So let's change your code a bit. Extract processMessage function (now it is async) and call processMessage with correct parameters:
function processMessage(vMsg, msErr, callback) {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg) {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
callback(msErr); // <-- return result
}
function dovalidation(callback) {
var vMsg = "", msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate = "";
var vLastRunDate = "";
var sStatus = "";
var sResponse = "";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0) {
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value = sStatus;
}
if ((vEffectiveDate).length > 0) {
if (!isDate(vEffectiveDate)) {
vMsg = vMsg + "[Effective Date] Is not a date." + ";\r\n";
} else if (moment(toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate))) {
vMsg = vMsg + "[Effective Date] cannot be on/before " + vLastRunDate + "." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content: "Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse = 1;
vMsg = "Response 1";
processMessage(vMsg, msErr, callback); // <--- added this
},
cancel: function() {
sResponse = 2;
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function() {
document.getElementById("Smoke.Calc Status").value = "REFRESH";
msErr = "ABORT";
processMessage(vMsg, msErr, callback); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage(vMsg, msErr, callback); // <--- added this
}
}
//#################
}
Note: this code is not "clean". If this function dovalidation you showed us has full code, then you can clean the code. This code is runnable (better use it in fullscreen), but I still do not understand what you are trying to do...
const isDate = (x) => true; // Mock
const toDate = (x) => x; // Mock
function processMessage(mType, vMsg, msErr, callback, sResponse) {
if (vMsg) {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR"; // ???
}
callback(mType, msErr, vMsg, sResponse); // <-- return result
}
function dovalidation(callback) {
var sResponse = "";
let vMsg = '';
let msErr = '';
let vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
let vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
let sStatus = document.getElementById("Smoke.Calc Status").value;
if (!sStatus) {
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value = sStatus;
}
if (vEffectiveDate) {
if (!isDate(vEffectiveDate)) {
vMsg = vMsg + "[Effective Date] Is not a date.;\r\n";
} else if (moment(toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate))) {
vMsg = vMsg + "[Effective Date] cannot be on/before " + vLastRunDate + ".;\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content: "Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: () => {
sResponse = 1;
vMsg = "Response 1";
processMessage('Confirm', vMsg, msErr, callback, sResponse);
},
cancel: function() {
sResponse = 2;
vMsg = "Response 2";
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: () => {
document.getElementById("Smoke.Calc Status").value = "REFRESH";
msErr = "ABORT";
processMessage('Abort', vMsg, msErr, callback, sResponse);
}
});
},
}
});
} else {
processMessage('Success', vMsg, msErr, callback, sResponse);
}
}
function test() {
dovalidation(function(mType, msErr, vMsg, sResponse) {
console.log('[TYPE]', mType, '[RESULT]', msErr || '?', '[MESSAGE]', vMsg || '?');
//if (result != "") {
// return;
//}
});
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<input type="text" id="Smoke.Effective Date" value="2020-01-02"/>
<input type="text" id="Smoke.Last Run Date" value="2020-01-01"/>
<input type="text" id="Smoke.Calc Status" value="WTF?"/>
<button onclick="test()">TEST</button>
The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {
I am trying to validate drop down in js. Here is my script code
$.validator.addMethod(
'drop_down_validation',
function (value, element) {
alert ("my_fun")
var val = $('#creative_offer_type').val();
alert (val);
if (value.length==0 && val=="") {
return false;
}
else return true;
},
$.format("must select atleast one value")
);
var form_rules = {
'creative[offer_type]' : {
required: true,
drop_down_validation: true
},
};
var form_messages = {
'creative_offer_type' : { required: 'You must specify Offer Type'},
};
Is is correct? I tried out like this, but doesn't show any response in UI.
For your reference
function JSFunctionValidate()
{
if(document.getElementById('<%=ddlView.ClientID%>').selectedIndex == 0)
{
alert("Please select ddl");
return false;
}
return true;
}
Just call this method in your dropdown..
I have two questions from the coding below.
First, now i would like to perform validation before submission. How can I stop submission if some errors are detected from the validation function? Is it simply return false after each of the error msg? however, it seems still check all fields instead of stopping after getting one error.
Second, i would like to insert the data via php. Everytime, it can successfully add the data to the database, however, it always alert "Error: error". I dunno where does the error come from...
$(document).ready(function()
{
$('#test').click(function(){
validation();
});
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
}
else
{
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
}
else
{
}
//return false;
} // end of #validation
$('form').submit(function(){
validation();
$.ajax({
type: 'POST',
data:
{
loginID: $("#loginID").val(),
// some data here
},
url: 'http://mydomain.com/reg.php',
success: function(data){
alert('successfully.');
},
error: function(jqXHR, textStatus){
alert("Error: " + textStatus);
}
});
return false;
});
});
you can use return false.It will stop the execution
<form onSubmit="validatdeForm();"></form>
function validatdeForm()
{
//here return true if validation passed otherwise return false
}
or
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
it should be something like below. return false stop execution of script when error is there.
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
else
{
return true;
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
else
{
return true;
}
return true;
} // end of #validation
Design your validation function as below,
function validation()
{
var isValid = true;
if(field validation fail)
{
isValid = false;
}
else if(field validation fail)
{
isValid = false;
}
return isValid;
}
basic idea behind code is to returning false whenever your validation fails.
To make a proper form validation, I will suggest you go about doing it in a more organized way. It is easier to debug. Try this:
var validation = {
// Checking your login ID
'loginID' : function() {
// Login ID validation code here...
// If a validation fails set validation.errors = true;
// Additionally you can have a validation.idError that contains
// some error message for an id error.
},
// Checking your password
'loginPW' : function() {
// Password validation code here...
// If a validation fails set validation.errors = true;
// As with id, you can have a validation.pwError that contains
// some error message for a password error.
},
'sendRequest' : function () {
if(!validation.errors) {
// Code for whatever you want to do at form submit.
}
}
};
$('#test').click(function(){
validation.errors = false;
validation.loginID();
validation.loginPW();
validation.sendRequest();
return false;
});
function validateimage() { if($("#photo").val() !== '' ) {
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_file = document.form_useradd.photo.value;
var image_length = document.form_useradd.photo.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert(" Upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
//$("#error-innertxt_photo").show().fadeOut(5000);
//$("#error-innertxt_photo").html('Enter valid file type');
//$("#photo").focus();
return false;
}
I have the following function:
function checkEmails(newEmail){
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
return false;
}
});
return true;
}
I'm calling it this way in my form submit handler:
if (!checkEmails($('input#email', $('#newForm')).val())) {
return false;
}//I submit the form via ajax next....
I'm just checking to make sure that the email address the user's trying to submit isn't already in a table. It seems to work good, except in Firefox, it doesn't actually stop the ajax request from occurring. The alert box appears, telling me the user's already in the list, but after clicking ok, the form is submitted anyway. It works as I want it to in IE.
What am I doing wrong here?
it should probably be done like this:
function checkEmails(newEmail){
var ret = true;
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
ret = false;
}
});
return ret;
}
What it is doing is setting the return value to true before doing the each on the elements to, then if it finds any invalid email addresses it will set it to false. That is the value that will be returned from the function.
the return false is inside the closure so it doesn't break out of the outer function
i.e. it returns false for the nested function and not for checkEmails
I think you want this (use a bigFatGlobal to store the return value):
function checkEmails(newEmail){
var bigFatGlobal = true;
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
bigFatGlobal = false;
}
});
return bigFatGlobal;
}