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!
You manually trigger the button click event. Make sure type is button.
You do not need
**onsubmit=" return registerValidation()"**