表格不会提交返回虚假;

时间:2013-03-18 21:31:28

标签: jquery html

输入和textarea填写后,我的简单表单将不会提交。为便于阅读而编辑。

$(function () {
    $("#contactform").submit(function () {
        $(":input").not("[type=submit]").removeClass('error').each(function () {
            if ($.trim($(this).val()).length == 0) $(this).addClass('error');

        });            
        if($(document).hasClass("error")){
        return false;
}
    });
});


<form id="contactform" action="success.php" method="post">
  <input type="text" id="name" placeholder="name" autofocus >
  <input type="text" placeholder="email" >
  <textarea placeholder="message" ></textarea>
  <input type="submit">
  </input>
</form>

4 个答案:

答案 0 :(得分:1)

您正在使用return false;来阻止提交。只有当您想要停止提交表单时才使用它(例如验证中的错误等)

答案 1 :(得分:1)

每次都不要使用return false。检查输入是否有错误,如

return !!$('input.error').length;

答案 2 :(得分:1)

请勿使用return false;,这会停止提交。

将您的代码更改为以下内容:

    $(function () {
    $("#contactform").submit(function (e) {
        $(":input").not("[type=submit]").each(function () {
            if ($.trim($(this).val()).length == 0){ 
                $(this).addClass('error');
               e.preventDefault(); 
            }

        });

    });
});

答案 3 :(得分:1)

您应该在返回false之前检查是否有任何错误

$(function () {
    $("#contactform").submit(function () {
        $(":input").not("[type=submit]").removeClass('error').each(function () {
            if ($.trim($(this).val()).length == 0) $(this).addClass('error');    
        });
        // if there is anything with a class of error inside the form
        // can also use $(this).find('.error') - it's the same thing
        if($('.error',this).length){
            // then return false
            return false;
        }
    });
});

http://jsfiddle.net/D4F55/

相关问题