ASP.NET在表单onsubmit上调用DOM元素时消失

时间:2017-01-05 20:21:24

标签: javascript jquery asp.net onsubmit

我有简单的Html.BeginForm和一些数据,我想在用户点击时使用onsubmit()javascript函数检查一些条件"提交"按钮,表格将被发送。当这个条件为假时,我想停止重新加载页面,只是不要将我的表单发送到POST方法。这工作正常,我遇到了一个问题,因为我在onsubmit()方法中创建的 DOM元素消失了

 @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", **onsubmit=" return registerValidation()"**}))
    {
        @Html.AntiForgeryToken()

     @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @id = "emailVal"})
     @Html.ValidationMessageFor(m => m.Email,"", new { @class = "validation-error-white", @id="emailValidation"})

     <input type="submit" class="btn btn-warning btn-block add-item-button-text" value="Zarejestruj" />

    }


<script type="text/javascript">

   function registerValidation() {

            var validForm = validateRegisterForm(email, login);
            if (!validForm) {
                $('#emailValidation').append('Those email already exists! Take another one');
                return false;
            }
            return true;
        }
  </script>

因此,当我想要返回false,并且不发送表单时,我附加到validation-div的文本会说明错误消失了 - 它不是我想要实现的,因为它&# 39;非常小的时间段,用户甚至都注意不到!

1 个答案:

答案 0 :(得分:1)

您手动触发按钮单击事件。确保 类型 按钮

您不需要**onsubmit=" return registerValidation()"**

<input id="btnSubmit" type="button" ... />

<script type="text/javascript">

    $(function () {

        // Trigger btnSubmit button's click event, when enter key is pressed.
        // If you do not want that feature, you can ignore this. 
        $("form").keydown(function (event) {
            if (event.keyCode === 13) {
                $("#btnSubmit").click();
                return false;
            }
        });

        $("#btnSubmit").click(function () {
            // Do something, then submit the form
            $("form").submit();
        });
    });
</script>