0

我有一个使用 jQuery 定义的自定义验证器,它检查以确保在 HTTPPost 发生之前完成必填字段。我的脚本如下:

<script>
$(document).ready(function() {
    $('#ContentProperties').hide();
    $('#FileSubmit').hide();
});

$(function () {
    $("input:file").change(function () {
        var fileName = $(this).val();
        if(fileName != null)
            $('#FileSubmit').show();
            $('#ContentProperties').show();
            alert("File successfully chosen please enter required metadata below");
    });
});

$(document).ready(function () {
    $("#FileSubmit").click(function () {
        var name = document.getElementById("name").value;
        var author = document.getElementById("author").value;
        var description = document.getElementById("description").value;
        var uploadDate = document.getElementById("uploaddate").value;
        var expiryDate = document.getElementById("expirydate").value;
        var contentType = document.getElementById("contenttypeid").value;
        var alertString = "";

        if (name.length == 0) {
            alertString += "NAME: You must enter a name for your content!\n" 
        }

        if (author.length < 6) {
            alertString += "AUTHOR: You must enter at least 6 characters for author!\n"
        }

        if (description.length < 20) {
            alertString += "DESCRIPTION: You must enter a valid description of at least 20 characters !\n"
        }

        if (uploadDate.length < 8 || uploadDate.length > 10) {
            alertString += "UPLOAD DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (expiryDate.length < 8 || expiryDate.length > 10) {
            alertString += "EXPIRY DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (alertString.length > 0) {
            alert(alertString)
            event.cancelBubble = true;
            event.returnValue = false;
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
    });
});

当我单击提交按钮且验证字段留空时,它会正确显示错误消息,但无法停止发布。使用 jQuery 时如何执行此操作?以前我只使用过 javascript,并且可以使用以下方法停止冒泡:

event.cancelBubble = true;
event.returnValue = false;
event.preventDefault();
event.stopPropagation();
4

2 回答 2

1

您没有在函数调用中引用“事件”:

$("#FileSubmit").click(function (event) { ....
于 2013-07-17T16:09:20.067 回答
1

你还没有定义event

$("#FileSubmit").click(function (event) {

虽然我通常e用作约定:

$("#FileSubmit").click(function (e) {
    e.preventDefault();
});

旁注:我会将其更改为将处理程序附加到表单提交,而不是单击提交按钮。您可以通过按 Enter 提交表单,它会跳过您的点击处理程序。

于 2013-07-17T16:07:48.530 回答