最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery submit event and return false - Stack Overflow

programmeradmin2浏览0评论

hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page

$('#loginAccount').submit(function() {
    $(this).find(':input:text').each(function(i) {
        if($(this).val()=="") {
            // alert($('label').eq(i).html())
            $('#alert3').html('Please fill all fields.');
            return false;
        }
    });
});

hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page

$('#loginAccount').submit(function() {
    $(this).find(':input:text').each(function(i) {
        if($(this).val()=="") {
            // alert($('label').eq(i).html())
            $('#alert3').html('Please fill all fields.');
            return false;
        }
    });
});
Share Improve this question edited Feb 28, 2012 at 9:10 Mark Bell 29.8k26 gold badges121 silver badges150 bronze badges asked Feb 3, 2010 at 15:03 dexameldexamel 336 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7
$('#loginAccount').submit(function() {
    var valid = true;
    $(this).find(':input:text').each(function(i) {
        if($(this).val() == "") {
            // alert($('label').eq(i).html())
            $('#alert3').html('Please fill all fields.');
            valid = false;
        }
    });
    return valid;
});

You are currently returning from the each. What you need to do is track whether it's valid and then use that value as the return from your submit.

return false; takes on a different meaning inside of a jQuery each(). It is used to break out of the each. Maybe you could set a flag that is observed after the each() to see if the validation succeeded.

You need to return false in the submit function, not the each function:

$('#loginAccount').submit(function() {
    var isValid = true;
    $(this).find(':input:text').each(function(i) {
        if($(this).val()=="")
        {
            isValid = false;
            //alert($('label').eq(i).html())
            $('#alert3').html('Please fill all fields.');

        }
    });
    return isValid;
});

May be you shoul use closure to return a value?

    $('#loginAccount').submit(function() {
           var result = true;    
            $(this).find(':input:text')
                 .each(function(i) {
                if($(this).val()=="")
                {
                    //alert($('label').eq(i).html())
                    $('#alert3').html('Please fill all fields.');
                    result = false;
                }
            });
            return result;
            })
发布评论

评论列表(0)

  1. 暂无评论