如何阻止表单提交?

时间:2013-08-28 10:22:46

标签: jquery html css

如何停止提交表单? 我的表单上有一些验证,如果输入不正确,那么表单不应该提交... 在我的HTML中,我点击提交时有这个:

<a href="#" onclick="setTimeout(function(){document.getElementById('form_4').submit()}, 1000);" style="position:static" class="btn-more">Vælg</a>

我的脚本看起来像这样:

$("#form_4 a.btn-more").click(function (e) {

    //Validate required fields
    for (i = 0; i < required.length; i++) {
        var input = $('#' + required[i]);

        if ((input.val() == "") || (input.val() == emptyerror)) {
            input.addClass("needsfilled");
            input.val(emptyerror);
            errornotice.fadeIn(750);
            e.stopPropagation();
            return false;
        } else {
            input.removeClass("needsfilled");
        }
    }
    //if any inputs on the page have the class 'needsfilled' the form will not submit
    if ($(":input").hasClass("needsfilled")) {
        return false;
    } else {
        errornotice.hide();
        return true;
    }
});

5 个答案:

答案 0 :(得分:2)

使用:

e.preventDefault();  

关闭点击功能之前或开始时

$("#form_4 a.btn-more").click(function(e){  
    e.preventDefault();  
    //rest of the content
}

您还应该按照您的方式更改setTimeout function,它始终会提交表单。改为:

HTML:

<a href="#" style="position:static" class="btn-more">Vælg</a>

脚本:

$("#form_4 a.btn-more").click(function (e) {

    //Validate required fields
    for (i = 0; i < required.length; i++) {
        var input = $('#' + required[i]);

        if ((input.val() == "") || (input.val() == emptyerror)) {
            input.addClass("needsfilled");
            input.val(emptyerror);
            errornotice.fadeIn(750);
            e.stopPropagation();
            return false;
        } else {
            input.removeClass("needsfilled");
        }
    }
    //if any inputs on the page have the class 'needsfilled' the form will not submit
    if ($(":input").hasClass("needsfilled")) {
        e.preventDefault();  
        return false;
    } else {
        errornotice.hide();
        return true;
    }
});

答案 1 :(得分:0)

永远不要在HTML内联中使用javascript函数。将所有JS放在js文件中。

然后,使用你喜欢的

 if ($(":input").hasClass("needsfilled")) 
    {
        return false;
    } 
    else 
    {
        errornotice.hide();
        $("#form_4").submit()
    }

当一切正常时,只需致电表单提交。

答案 2 :(得分:0)

onclick="return false";

这将阻止提交。

  来自jQuery事件处理程序的

return false 实际上是   与调用 e.preventDefault e.stopPropagation 相同   传递了jQuery.Event对象。

$("#form_4 a.btn-more").click(function (e) {
 return false;
}

答案 3 :(得分:0)

errornotice.hide();
return true;

删除return true;并添加行

document.getElementById('form_4').submit();

$(".form4").submit();

并从链接标记中删除onlick函数

<a href="#"  style="position:static" class="btn-more">Vælg</a>

答案 4 :(得分:-1)

$(".form4").on("submit", function () {
});

如果值返回false,则表示不提交