Reputation: 121
I have simple Html.BeginForm with some data, and i want to check some condition using onsubmit() javascript function when user clicked "submit" button, before form will be send. And when this condition is false, I want to stop reloading page, just don't send my form to POST method. This is working fine, bit I met a problem, because DOM elements which I create in onsubmit() method disappear:
@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>
So when I want to return false, and do not send form, text that I append to validation-div that says what's wrong disappear - it's not what I want to achieve, because it's very small period of time and user cannot even notice that!
Upvotes: 0
Views: 448
Reputation: 62260
You manually trigger the button click event. Make sure type is button.
You do not need **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>
Upvotes: 1