开发者

How to stop function from running in javascript, jquery?

开发者 https://www.devze.com 2022-12-17 07:48 出处:网络
I have the following function: function checkEmails(newEmail){ $(\'table td:nth-child(3)\').each(function(){

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消