简体   繁体   English

jQuery / JavaScript表单验证不起作用

[英]jQuery/JavaScript form validation is not working

I am using this code for form validation, 我正在使用此代码进行表单验证,

$("#btnaddregistration").live("click", function(e) {
    e.preventDefault();
    var errorCount = 0;
    $("#formaddregistration").find("input").each(function(i) {
        if ($(this).val().length == 0) {
            errorfield = $(this);
            errorCount++;
            $("#modaldialogtext").text("'" + $(this).parent().parent().find("label").text() + "' cannot be left blank.");
            $("#modal_confirmation").dialog("open");
            return false;
        }
    });
    if (errorCount > 0) {
        return false;
    } else {
        document.forms["formaddregistration"].submit();
    }
});​

But form is not submitting. 但是表格没有提交。 I have used all possible submit methods but I failed. 我已经使用了所有可能的提交方法,但是失败了。 Any idea where I am getting wrong? 知道我哪里出错了吗?

First, you can improve your code quite a lot, that will help you in troubleshooting. 首先,您可以极大地改进代码,这将有助于您进行故障排除。

If the form is not submitting, make sure that the selector is actually working, ie, try something like $form.hide() and see if it hides, to ensure that it's not PEBCAK 如果没有提交表单,请确保选择器确实在工作,即尝试使用$form.hide()类的东西,看看它是否隐藏,以确保它不是PEBCAK

var $form = $("#formaddregistration");
$("#btnaddregistration").on("click", function(e) {
    var errorCount = 0;


    $form.find("input").each(function(i) {
        var $this = $(this);
        if ($this.val().length < 1) {
            errorCount++;

            // this line also needs improving..
            $("#modaldialogtext").text("'" + $this.parent().parent().find("label").text() + "' cannot be left blank.");
            $("#modal_confirmation").dialog("open");
            return false;
        }
    });

    if (errorCount < 1) {
        $form.submit();
    }

    return false;
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM