我有一些简单的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>
“那!type是button。
您不需要**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>