return false不会阻止表单提交

时间:2013-11-30 13:59:39

标签: javascript jquery forms

我有一个表单,我正在尝试对其进行一些验证,以捕获旧浏览器和Safari(!)上的必填字段。我到目前为止的解决方案似乎几乎工作......当我在Safari上提交带有空字段的表单时,弹出错误,然后无论如何都会提交表单。我做错了什么?

我的表单如下:

<form id="primaryPostForm" method="POST" >

<input type="text" name="iName" id="iID" maxlength="25" required="required" value="" />

<textarea class="tipContent requiredAttr" name="taName" id="taID" maxlength="150" required="required" ></textarea> 

<input type="hidden" name="submitted" id="submitted" value="true" />
<input id="submitBtn" type="submit" value="Submit">

我的验证如下:

function validate(){
$('#primaryPostForm').submit(function(){
    $("#primaryPostForm .requiredAttr").each(function(){
        if($(this).val().length < 1){
        alert("Please make sure the fields are filled in - thanks");
        return false;}
    })//end each
})//end submit
}

3 个答案:

答案 0 :(得分:2)

return false仅从each循环退出。您需要存储可以从函数返回的结果:

function validate(){
  $('#primaryPostForm').submit(function(){
    var result = true;
    $("#primaryPostForm .requiredAttr").each(function(){
        if($(this).val().length < 1){
        alert("Please make sure the fields are filled in - thanks");
        result = false;
        return false; // exit loop
      }
    })//end each
    return result;
  })//end submit
}

答案 1 :(得分:1)

首先,请使用e.preventDefault();代替return false

回答你的问题: return false必须在提交事件回调范围内:

function validate(){
    $('#primaryPostForm').submit(function(e){
        var ret = true;
        $("#primaryPostForm .requiredAttr").each(function(){
            if($(this).val().length < 1){
                alert("Please make sure the fields are filled in - thanks");
                ret = false;    
            }
        });
        if(!ret){
            e.preventDefault();
        }
    });
}

更简洁直接的方法是:

$('#primaryPostForm').submit(function(e){
    var required = $(".requiredAttr", this).filter(function(){
        return !this.value;
    });
    if(required.length){
        alert("Please make sure the fields are filled in - thanks");
        e.preventDefault();
    }
});

答案 2 :(得分:0)

试试这个,请参阅MDN

function validate(){
$('#primaryPostForm').submit(function(){
    var result = [];
    $("#primaryPostForm .requiredAttr").each(function(){
        if($(this).val().length < 1){
        result.push(false);
        }
    })//end each
    result.some(function(element){return (element!=false)})
    alert("Please make sure the fields are filled in - thanks");
})//end submit
}
相关问题