jQuery - 如何在显示警报消息后阻止表单发布数据?

问题描述 投票:-1回答:1

如果未填写出生日期,我想阻止用户发布表单数据。我使用了如下所示的一些脚本来防止用户在未插入出生日期但是仍然发布表单时发布数据。

以下是我的表格:

@using (Html.BeginForm("TutorRegister", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{       
        <div class="form-group col-sm-4 col-md-4 col-lg-4">
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Email)
        </div>
        <span class="clearfix"></span>

        <div class="form-group col-sm-4 col-md-4 col-lg-4">
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Password)
        </div>
        <span class="clearfix"></span>


        <div class="form-group col-sm-4 col-md-4 col-lg-4">
            <label>Date of Birth</label>
            <div class="input-group date" id="dtp">
                <input name="Birthday" id="Birthday" class="form-control" onfocus="$(this).next().trigger('click')" onkeydown="event.preventDefault()" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
            @Html.ValidationMessageFor(m => m.Birthday)
        </div>
        <span class="clearfix"></span>                

        <div class="form-group col-sm-4 col-md-4 col-lg-4">
            <input id="btnRegister" type="submit" class="btn btn-default" value="Register" />
        </div>

    </div>
}

以下是脚本:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(document).ready(function () {
            $("#btnRegister").click(function () {
                if (document.getElementById('Birthday').value == "") {
                    alert("You need to fill Date of Birth field!");
                    return;
                }
            })
        })           
    </script>
}

上面的代码确实显示了警告,点击确定后我希望表单不被发布。

谢谢

jquery html forms asp.net-mvc-5
1个回答
2
投票

您应该使用事件的preventDefault方法取消默认操作:

        $("#btnRegister").click(function (e) {
            if (document.getElementById('Birthday').value == "") {
                e.preventDefault();
                alert("You need to fill Date of Birth field!");
                return;
            }
        })

注意:您需要指定函数参数才能访问事件对象。

© www.soinside.com 2019 - 2024. All rights reserved.